6.2.2 trigger
注册了事件,如onclick。那么当用户点击这个元素时,就会自动触发这个事件的已经注册的事件处理函数。但是我们有的时候要采用程 序来模拟事件的触发就得采用强迫触发某个事件。在IE中我们可以采用.fireEvent()来实现。如:<form onsubmit="a()" >中,如果button的form.submit()的方式提交表单,是不会主动触发onsumbit事件的,如果必须的话,就要在submit 前$(“:form”)[0].fireEvent("onsubmit”,),这样就会触发该事件。
在mozilla中有三个步骤: var evt = document.createEvent('HTMLEvents');
evt.initEvent('change',true,true); t.dispatchEvent( evt );
在 prototype是采用这样的方式来实现的。那么jquery中呢,它的实现方式有一点不一样。
trigger : function(type, data, fn) {
return this.each(function() {
jQuery.event.trigger(type, data, this, true, fn);
}); },
Trigger有三个参数,data参数是为了注册的事件函数提供了实传。如果data[0]中preventDefault存在,data[0]就可 以做为用户自定义的包裹事件的空间。Fn是可以为事件提供一个即时即用的事件处理方法。也就是在没有注册事件的情况下也可以通过传入处理函数来处理事件。 如果已经注册了,那就是在原来的事件处理函数之后执行。
//这个方法将会触发指定的事件类型上所有绑定的处理函数。但不会 执行浏览器默认动作.
triggerHandler : function(type, data, fn) {
return this[0]&& jQuery.event.trigger(type,data,this[0],false,fn);
},
triggerHandle通过把jQuery.event.trigger的donative参数设为false,来阻止执行浏览器 默处理方法。它与trigger不现的一点,还在于它只是处理jquery对象的第一个元素。
上面两个方法都调用了 jQuery.event.trigger来完成任务:
trigger : function(type, data, elem, donative, extra) {
data = jQuery.makeArray(data);//data可以为{xx:yy}
//支持getData!这样的形式,exclusive = true表现会对add的注册的
//事件的所有函数进行命名空间的分种类的来执行。
if (type.indexOf("!") >= 0) { ①
type = type.slice(0, -1);var exclusive = true;
}
if (!elem) {// 处理全局的fire事件 ②
if (this.global[type])
jQuery.each(jQuery.cache, function() {
// 从cache中找到所有注册该事件的元素,触发改事件的处理函数
if (this.events && this.events[type])
jQuery.event.trigger(type, data, this.handle.elem);
});
} else {// 处理单个元素事件的fire事件 ③










