如何使用jquery发出事件?

时间:2014-03-14 14:31:47

标签: javascript jquery events

我试图创建一个简单的类来在某个时刻发出事件。 我得到这个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);

有什么建议吗?谢谢!

1 个答案:

答案 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');