2012-05-17 149 views
0

我已經爲jQuery編寫了一系列插件,它們實際上充當移動瀏覽器的事件。你可以在這裏看到它們>http://ben-major.co.uk/2011/11/jquery-mobile-events/在jQuery中觸發用於live的自定義事件()

目前,他們被稱爲$(ele).tap(handler)等等,但我想添加功能來引發自定義事件,以便可以使用像$(ele).on('tap', handler);這樣的東西來利用函數。

我使用下面的代碼的權利,但這似乎並沒有工作:

$(function() { 
    $('*').tapstart(function() { $(this).trigger('tapstart'); }) 
      .tapend(function() { $(this).trigger('tapend'); }) 
      .tap(function() { $(this).trigger('tap'); }) 
      .doubletap(function() { $(this).trigger('doubletap'); }) 
      .taphold(function() { $(this).trigger('taphold'); }) 
      .swipedown(function() { $(this).trigger('swipedown'); }) 
      .swipeup(function() { $(this).trigger('swipeup'); }) 
      .swipeleft(function() { $(this).trigger('swipeleft'); }) 
      .swiperight(function() { $(this).trigger('swiperight'); }); 
}); 

這裏有一個jsFiddle來證明我的問題。很明顯,點擊第二個div應該模仿第一個的動作,但是因爲在解析上面給出的綁定之後它被添加到DOM,所以它不會。

我想我的問題是:什麼是實現我想要的最好方法?有沒有辦法選擇DOM中現在和將來存在的所有元素(如果可能,我寧願不使用類似livequery或外部插件的東西)。

回答

1

在你的情況,我不認爲jQuery會正確處理你的自定義事件(因爲自定義事件不會冒泡到文檔中)。答案是將事件偵聽器的一個分支綁定到document。並且不要在這種情況下使用jQuery。 jQuery的實時模式幾乎和我的建議一樣,但它會嘗試將event.target與綁定選擇器(在你的問題中說'*')相匹配,這是非常慢的手機)。

如果你想與特定的類型或某個className的元素進行交互,只需通過你自己處理它,然後觸發所需的事件處理程序。

一個例子:

function findAncestorOfType(el, type) { 
    while (el && !(el instanceof type)) 
    el = el.parent; 
    return el; 
} 

document.addEventListener('click', function(evt) { 
    var target = findAncestorOfType(evt.target, LIElement); 
    if (target) { 
    // distinguish event type 
    type = 'click'; 
    callbacks[type](target, evt); 
    } 
}, false); 
+0

我結束了重寫基於一些對你評論的事件庫。你是對的 - 使用jQuery'*'選擇器對於移動設備來說是一個不好的判斷。 – BenM