我有下面的代碼:如何創建和Singleton類中的事件處理程序 - 的Javascript
// Singleton
var mySingleton = (function() {
// Private methods and variables
function privateMethod(){
console.log("I am private");
}
var privateVariable = "Im also private";
return {
// Public methods and variables
hello: function() {
console.log("I want to ''fire'' the event 'hello'");
}
};
})();
而且我要創造我自己的事件處理系統。我試着用下面的代碼:
var mySingleton = (function() {
function privateMethod(){
console.log("I am private");
}
var handlers = {};
mySingleton.prototype.registerHandler = function(event, callback) {
this.handlers[event] = callback;
};
mySingleton.prototype.fire = function(event) {
this.handlers[event]();
};
var privateVariable = "Im also private";
return {
hello: function() {
console.log("I want to ''fire'' the event 'hello'");
fire('hello');
}
};
})();
我使用方法如下:
mySingleton .registerHandler('hello', function() {
alert('Hi!');
});
但是,這並不工作...我扔了一個錯誤:
Cannot read property 'prototype' of undefined
有人可以幫我嗎?
我目前的錯誤:
Uncaught TypeError: Cannot set property 'mycustomevent' of undefined
Uncaught TypeError: Cannot read property 'mycustomevent' of undefined
您好,感謝您的校正。但是...當我嘗試使用它: mySingleton .registerHandler( 'mycustomevent',函數(){ ... }); 和mySingleton.fire('mycustomevent'); 扔我的下一個錯誤: 遺漏的類型錯誤:無法設置未定義 遺漏的類型錯誤的特性「mycustomevent」:無法讀取的不確定 財產「mycustomevent」願你能幫助我,好嗎? – MartaGom 2014-12-07 16:22:53
¡對不起!我忘了刪除「這個」參考。它工作太棒了。非常感謝:) – MartaGom 2014-12-07 16:37:56
@MartaFernandez好吧,我很高興它爲你工作! – Pointy 2014-12-07 16:48:49