【问题标题】:custom events to constructor javascript构造函数javascript的自定义事件
【发布时间】:2013-04-05 18:38:48
【问题描述】:
javascript 新手。我有一个非 DOM 函数,我想向构造函数添加事件。
var class=function(){
/*
some code
*/
}
class.prototype.add=function(){
/*
adding item*/
}
现在我想向 custructer 添加事件
var klass=new class;
class.onadd(function(){
/*execute on adding item*/
});
我会多次附加不同的功能。
如何添加事件和调用函数?
【问题讨论】:
标签:
javascript
jquery
oop
prototype
【解决方案1】:
它分为两部分,收集处理程序的on 和事件触发器,在你的情况下是add
on根据分配的事件收集处理程序:
function yourConstructor(){
this.events = {};
}
yourConstructor.prototype.on = function(eventName,handler){
//create a property in `this.events` called `eventName` and put an array
//in that array, store all handlers for that `eventName`
}
然后您的函数,在本例中为 add,执行其特定的处理程序:
yourConstructor.prototype.add = function(){
//do what add does
//then execute all handlers in this.events.add array
}
【解决方案2】:
您可以实现自己的事件系统,但我不建议这样做。已经有很多好的图书馆。这里有一些:
我创建了一个jsFiddle 来展示如何使用微事件。
function Person(name) {
this.name = name;
}
Person.prototype.sayName = function () {
alert('My name is ' + this.name);
this.trigger('nameSaid'); //trigger the nameSaid event
};
//Make Person instances observable by applying the MicroEvent mixin
MicroEvent.mixin(Person);
//Create a new Person instance
var o = new Person('John Doe');
//Listen to the nameSaid event
o.bind('nameSaid', function () {
alert(this.name + ' just said it\'s name!');
});
o.sayName();