我试图创建一个简单的类来在某个时刻发出事件。 我得到这个javascript错误:this.emit不是函数
这是代码:
var class_test = function(){};
class_test.prototype = {
some_property: null,
doSomething: function(msg) {
this.some_property = msg;
this.emit("somethingHappened");
}
};
var test = new class_test();
test.doSomething('Example');
test.addEventListener('somethingHappened',function(){
alert("Event");
},false);
有什么建议吗?谢谢!
答案 0 :(得分:3)
使用jQuery,因为你提出了它:
var class_test = function(){
this.dispatcher = $({});
};
class_test.prototype = {
some_property: null,
doSomething: function(msg) {
this.some_property = msg;
this.dispatcher.trigger("somethingHappened");
}
};
var test = new class_test();
test.dispatcher.on('somethingHappened',function(){
alert("Event");
});
test.doSomething('Example');