首页 > JQuery1.10.2中.trigger("click!")在click后添加叹号失效

JQuery1.10.2中.trigger("click!")在click后添加叹号失效

在《锋利的JQuery》第二版中有这样一段代码

$("div").bind("click", function(){  
    alert("click only");  
});  
$("div").bind("click.plugin", function(){  
    alert("click plugin");  
});  
$("#btn").click(function(){  
    $("div").trigger("click!");//在click后添加叹号,则只触发不在命名空间内的事件  
});  

但是

$("div").trigger("click!");//在click后添加叹号,则只触发不在命名空间内的事件

似乎只能在1.7.2中使用,而在最新的1.10.2中失效。
没有找到相应文档...求指导

补充说明:
原书的实例在JQ1.7.2中可以实现,然是1.10.2中无法实现。


这里应该是原书的一处笔误,反正我在实际使用中没有使用过trigger('click!')这种用法,参见
http://jsfiddle.net/Q7m7M/


UPDATE 2014.1.17 这个事情背后其实有个故事,如果你愿意看的话:http://www.soulteary.com/2014/01/17/jquery-trigger-changes.html

简单的来说,原因如下:
首先,1.7.2的代码中的定义是这样,关键代码是它:type.slice(0, -1);

trigger: function( event, data, elem, onlyHandlers ) {
    //省略一堆...
    if ( type.indexOf( "!" ) >= 0 ) {
        // Exclusive events trigger only for the exact event (no namespaces)
        type = type.slice(0, -1);
        exclusive = true;
    }

    if ( type.indexOf( "." ) >= 0 ) {
        // Namespaced trigger; create a regexp to match event type in handle()
        namespaces = type.split(".");
        type = namespaces.shift();
        namespaces.sort();
    }
    //省略一堆...
}

接着来看你说的最新版的1.10.2的代码:

trigger: function( event, data, elem, onlyHandlers ) {
    var handle, ontype, cur,
        bubbleType, special, tmp, i,
        eventPath = [ elem || document ],
        type = core_hasOwn.call( event, "type" ) ? event.type : event,
        namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];

    cur = tmp = elem = elem || document;

    // Don't do events on text and comment nodes
    if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
        return;
    }

    // focus/blur morphs to focusin/out; ensure we're not firing them right now
    if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
        return;
    }

    if ( type.indexOf(".") >= 0 ) {
        // Namespaced trigger; create a regexp to match event type in handle()
        namespaces = type.split(".");
        type = namespaces.shift();
        namespaces.sort();
    }
    //省略一堆...
}

差异一目了然,新版本去掉了对带有!的字符串的支持,所以也就是你所说的不能用了。
官方对于非公开API的取消没有发布任何文档,但是有commit说明,感兴趣的话,可以看看我文章开头给的链接。

如果你还是想实现同样的效果,不妨在自定义事件内添加参数判断。

【热门文章】
【热门文章】