我有下一个代码:
// 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