2014-10-06 63 views
0

我知道我有能力使用jQuery的$ .fn.on,off和trigger函數命名空間事件。是否可以設置一個能夠偵聽特定命名空間中的所有事件的處理程序?jQuery事件命名空間中的所有事件的一個監聽器?

如:

$(window).on(".event_namespace", function(e){ 
    //handler 
}); 

$(window).trigger("testEvent.event_namespace"); 
$(window).trigger("testEventTwo.event_namespace"); 

與預期的行爲是聽者會捕獲任何事件觸發與指定的命名空間...

最終的目標很簡單,就是能夠聽一些事實上會被我無法訪問的代碼觸發。我希望能夠說,「只需將你的事件添加到這個命名空間」,然後能夠捕獲那些,而不需要知道事件名稱本身;只有命名空間。

可能嗎?

+1

難道這是任何幫助:http://stackoverflow.com/questions/9735608/how-to-bind-to -all-custom-events-in-jquery – cjs1978 2014-10-06 22:47:57

回答

2

編輯,更新

嘗試

var ns = ".event_namespace", log = []; 

    // place below block at bottom of script block , 
    // after `n` events attached to `n` window, document, elements 

    // listen for events having `ns` namespace , 
    // attached to `window, document, "*"` , above 
    $(window, document, "*").on("event", function(e, ns, type) { 
     // do stuff when event having `ns` occurs 
     log.push([ns, type]); 
     $("#log").html("type, namespace: " + log.slice(-1) 
         + "<br> total <i>" + ns + "</i> events: " 
         + log.length) 
    }); 

    // if dynamic elements , events later attached , 
    // re-run this piece to add `event` event to those elements 
    $.each([window, document, $("*")], function(k, v) { 
     if($._data(v, "events") !== undefined) { 
      $.each($._data(v, "events"), function(key, val) { 
       if (val[0].namespace === ns.slice(- (ns.length -1))) { 
        $(v).on(key + ns, function(e) { 
         $(e.target).trigger("event", [e.namespace, e.type]) 
        }) 
       } 
      }) 
     } 
    }); 

的jsfiddle http://jsfiddle.net/guest271314/s87j4o6r/4/

+1

謝謝;主要的一點是不必知道事件類型;只有命名空間。我已經更新了這個問題。 – Dygerati 2014-10-08 15:56:53