2014-04-27 24 views
0

我看到的點擊事件被觸發的每一行上多次ItemView控件木偶ItemView控件點擊觸發多次

return Marionette.ItemView.extend({ 
    template: ItemViewTemplate, 
    tagName: 'tr', 
    className: 'ItemRow', 

    templateHelpers: viewHelpers, 

    events: { 
     'click .editRowItem': 'editRowItem' 

的editRowItem()函數被多次觸發。什麼纔是正確的方法來觸發在特定行上的點擊?

謝謝!

回答

2

通常它不應觸發多次。但是,可能會發生以下情況,例如:

  • 在視圖中具有相同類的嵌套元素。事件冒泡會導致多個事件被觸發。
  • 父視圖監聽某些或所有子視圖中存在的類上的單擊事件。

一個例子(剝離非相關部分):

<script type="text/template" id="movie-list-item"> 
    <button type="button" class="btn btn-success some-button"> 
     <span class="some-button">Click here</span> 
    </button> 
</script> 

// Itemview 
var movieItemView = Marionette.ItemView.extend({ 
    template: "#movie-list-item", 
    ui: { 
     viewButton: '.some-button' 
    }, 
    events: { 
     'click @ui.viewButton': 'clickHandler' 
    }, 
    clickHandler: function(ev) { 
     // Log the click 
     console.log('There was a click in an itemView!'); 

     // Uncomment the following to prevent multiple events: 
     //ev.stopPropagation(); 
    } 
}); 

// Composite view 
var movieCompView = Marionette.CompositeView.extend({ 
    template: "#movie-list", 
    itemView: movieItemView, 
    ui: { 
     viewButton: '.some-button' 
    }, 
    events: { 
     'click @ui.viewButton': 'clickHandler' 
    }, 
    clickHandler: function(ev) { 
     // Log the click 
     console.log('There was a click in a collectionView!'); 

     // Uncomment the following to prevent multiple events: 
     //ev.stopPropagation(); 
    } 
}); 

演示在這裏:http://jsfiddle.net/Cardiff/7d3fC/2/

注意以下,如果我們不使用這個ev.stopPropagation()爲防止事件冒泡,控制檯將記錄4個條目;兩個用於itemView,另外兩個用於collectionView。爲了防止這種行爲(並且在這種情況下,您不應該在collectionView中使用單擊事件),因此我們使用ev.stopPropagation()來接收一個而不是兩個事件。

另外請記住,使用視圖的ui屬性來描述組件被認爲是很好的做法,並且可以使您的生活變得更容易一些。

1

試試看以下,如果你想點擊事件應用到模板中的每一行項目:

events: { 
    'click' : 'editRowItem' 
}