2012-02-24 14 views
2

現在、iOSとAndroidの両方でwebappsを開発しています。ドキュメントツリーにない要素(iOS)のタッチイベントをバインドできません

iOSでタッチイベントをキャプチャしようとしていますが、要素をドキュメントツリーに読み込む前にそれを取得できません。ここにコードがあります。

var test1 = $("<div>").css({ 
width: "300px", 
height: "300px", 
"background-color":"#ff00ff" 
}); 
var test2 = $("<div>").css({ 
width: "100px", 
height: "100px", 
"background-color":"#ffff00" 
}); 

$(test1).append($(test2)); 

$(test1)[0].addEventListener("touchstart",function(){ 
    alert("listen addEventListener"); 
}); 
$(test1).bind("touchstart",function(e){ 
    alert("listen bind"); 
}); 
$(test1).on("touchstart","div",function(e){ 
    alert("listen on"); 
}); 

$("body").append($(test1)); 

私のiPadでは、body1の下にtest1を追加する前にこれらのコールバックをバインドするとタッチイベントが発生しません。 でもAndroid搭載の携帯電話では動作します。

タッチスタートからクリックまでリスニングイベントを変更すると、iOSでも動作します。

私はiOSに関するtoucheventについて迷っていることはありますか?

答えて

0

これが問題なら、追加後にイベントリスナーを追加しない理由はわかりません。なぜあなたは最初のtest1を追加してはならないのか分かりません.2

+0

私はBackbone.jsを使用して私のWebアプリケーションのイベントをバインドしています。 Backbone.jsはDOMツリーに追加する前にイベントをバインドします。このtest1とtest2はテスト目的のためだけです。要素を追加した後にイベントをバインドすることで解決できることは分かっていますが、なぜそれが機能しないのかがわかりません。 –

0

この問題を回避するには、タッチイベントリスナーを 'DOMNodeInserted'に追加して 'DOMNodeRemoved'-Eventで再度削除します。

0

私はこれも私の頭を叩いて約半分を失い、要素がDOMに入った後にイベントをフックするためのハックで終わった。私はMarionetteをBackboneのヘルパーライブラリとして使用しています...そのために、私の 'fixer'コードです。

// Normally, Marionette will register event handlers before elements are 
// added to the DOM. For touch-related events, Safari on iOS does not 
// like this... no error message, but the event handler will never be 
// invoked. 
// 
// Our workaround for this is to provide a default implementation for 
// 'onShow' 
// 
Backbone.Marionette.View.prototype.onShow = function() { 
    this.delegateEvents(); 
} 
// onShow is invoked by Marionette after views are added to the DOM... 
// but only if they are added to the DOM via a call to 
// region.show(view). For most views, this is sufficient. However, 
// for ItemViews within a CollectionView, there is never such a call. 
// For this case, we have a workaround within a workaround: have the 
// default onShow implementation for CollectionView loop over all of 
// its children (the ItemViews) and call onShow on them just as the 
// Marionette.Region would have done. 
Backbone.Marionette.CollectionView.prototype.onShow = function() { 
    this.delegateEvents(); 
    if (this.children) { 
     $.each(this.children, function(i, itemView) { 
      itemView.onShow(); 
     }); 
    } 
}