2012-04-16 46 views
10

是否有可能來聽一個基本事件的所有事件,如果事件是命名空間?jQuery的:綁定命名空間的事件

例子:

$elmt.bind("change", function (event) { 
    console.log(event); 
}); 
$elmt.trigger("change.namespace1"); 
$elmt.trigger("change.namespace2"); 

這隻能如果我綁定到完整的活動名稱,但是這是不知道在這個位置:(

+0

究竟是你想怎麼辦? – Evan 2012-04-16 15:41:52

+0

一個jQuery插件觸發命名空間變化事件(change.channel,change.selected等)。如果其中一個變更事件已經觸發,我想要採取行動。我不會硬編碼所有可能的命名空間。 – 2012-04-16 15:47:45

+0

在你的問題就來了,我張貼[礦]後(http://stackoverflow.com/questions/12590231/bind-to-all-namespaces-of-custom-jquery-event)。我也想知道這是可能的。 – jschr 2012-09-25 20:04:57

回答

1

你我可以,但它並不完美。

,例如:

function eventHandler(event){ 
    $("#output").html($("#output").html() + "<br />" + event); 
} 

$elmt = $("#elmt"); 
$elmt.bind("change.namespace1", eventHandler); 
$elmt.bind("change.namespace2", eventHandler); 

$elmt.trigger("change.namespace1"); 
$elmt.trigger("change.namespace2"); 

JSFiddle is here

你需要從事件中提取命名空間和上,雖然切換,既命名空間爲基本的「改變」事件幾乎意味着你需要使用「唯一」的命名空間,或者沒有命名空間解僱。

我希望這有助於一點。

1

交叉張貼從Bind to all namespaces of custom jquery event


嘗試triggerAll,而不是trigger

(function($) { 
    $.fn.triggerAll = function(topics, data, delimiter) { 
     return this.each(function() { 
      var $this = $(this), chain = [], t = ''; 
      delimiter = (delimiter || '.'); 
      // rebuild chain 
      $.each(topics.split(delimiter), function(i,n) { 
       t += (i == 0 ? '' : delimiter) + n; 
       chain.push(t); 
      }); 

      // append/prepend original topic? 
      data = (data || []); 
      data.push(topics); 
      $.each(chain, function(i,t) { 
       $this.trigger(t, data); 
      }); 
     }); 
    }; 
})(jQuery); 

誠然,由於jQuery的如何處理觸發命名空間,引發了 「根」 事件實際上觸發了命名空間的版本,因此要獲得你期望你需要使用另一個字符分隔符,像/,然後聲明您的活動像什麼:

var $o = $('#whatever'); 
// this will be triggered for all events starting with 'root' 
$o.on('root', function() { console.log(Array.prototype.slice.call(arguments, 0)); }); 
// some arbitrary way to fire custom events 
$o.on('click', function() { 
    $o.triggerAll('root/custom1/subA', ['1st', '2nd'], '/'); 
    $o.triggerAll('root/custom2', [3, 4, 5], '/'); 
}); 
+0

哎呦......不太對。 1秒。 – drzaus 2013-02-21 02:45:44

+0

更新,以匹配原來的職位。 – drzaus 2013-02-21 03:39:01

0

這是我用來比較各種li元素上現有的主題,並與新的自定義主題更換.....

$('li').each(function(index) { 
        var oT = $(this).attr('data-theme'); 
        var li_item = $(this).attr(index); 

        $('#li_item ').mousedown(function() { 

         if(oT=='a') 
         { 
          $(this).removeClass('ui-btn-up-' + a').addClass('ui-btn-up-' + 'c').attr('data-theme', 'c'); 
         } 

        }); 

        $('#li_item ').mouseup(function() { 


         if(oT=='c') 
         { 
          $(this).removeClass('ui-btn-up-' + 'c').addClass('ui-btn-up-' + 'a').attr('data-theme', 'a'); 
         } 

        }); 

});