我已经构建了一个dom对象引擎,它具有我在下面简化的私有/公共字段/方法:
function Engine(args){
this.display = args.display;
this.getDisplay = function(){return this.display;}
this.alertMsg = function(msg){
console.log(this.display);
alert(msg);
}
}
我想要做的是构建一个自定义事件,该事件将在警报(msg)之后触发,例如$(this.display).trigger(“afterAlert”);
function Engine(args){
this.display = args.display;
this.getDisplay = function(){return this.display;}
this.alertMsg = function(msg){
console.log(this.display);
alert(msg);
// trigger custom event here
$(this.display).trigger("afterAlert");
}
}
现在,这个事件可能是空的或不是.稍后声明的一个或多个对象如何注册到“afterAlert”事件?在我的情况下,主文件动态加载其他javascript文件,可能包含重新代码的代码:
function new_obj(){
bind("afterAlert", function(){
alert("alert was called");
});
}
解决方法:
从这个question看到我的答案…为了清楚起见重复了一遍
我将解决自定义事件的注册,触发和解除绑定.
jQuery具有注册,绑定和解除绑定到自定义事件所需的所有工具.
下面是将两个div连接到名为customAjaxStart的自定义事件的示例.然后我可以触发这个函数,两个处理程序都会被调用.
快速演示Here – 启用firebug / ie8控制台.
例如
$( function() {
$('#div1').bind('customAjaxStart', function(){
console.log('#div1 ajax start fired');
$(this).fadeTo('slow', 0.3);
});
$('#div2').bind('customAjaxStart', function(){
console.log('#div1 ajax start fired');
$(this).fadeTo('slow', 0.3);
});
//fire the custom event
$.event.trigger('customAjaxStart');
//unbind div1 from custom event
$('#div1').unbind('customAjaxStart');
//again trigger custom event - div1 handler will not fire this time
$.event.trigger('customAjaxStart');
});
以上面为例,我将从全局ajaxStart触发customAjaxStart.无论何时要进行xhr调用,都会自动触发任何侦听器(非常适合禁用小部件或显示加载的gif等),例如
$.ajaxStart( function(){
$.event.trigger('customAjaxStart');
});