2011-12-09 133 views
1

我想將兩個點擊事件綁定到兩個不同視圖中的單個HTML元素。其中一個意見觸發事件,另一個意見不觸發事件。綁定到backbone.js中的單個元素的多個視圖

其中一個視圖的主體爲el屬性。如果我將此視圖的el更改爲與其他視圖相同的元素,則會觸發這兩個事件。

這是預期嗎?如何在兩個不同視圖中爲同一元素綁定點擊事件?

+1

你能否提供一些代碼? –

回答

0

是的,這是預期的。主幹使用jQuery delegates進行事件綁定。這意味着,事件實際上綁定到視圖的EL,而不是直接綁定到子節點。

當你說,「相同的元素」,你的意思是字面上完全相同的節點在DOM?或者,你是否指具有相同選擇器的節點?我想我並不完全清楚。

0

我可以問你爲什麼想要2個視圖綁定到相同的元素?

從我的角度來看,你應該只有1個視圖來表示元素本身 並且綁定到元素的事件只能在該視圖中定義。

,當你點擊的結合事件不屬於視圖

元素,如果你綁定線槽delegateEvents哈希你會遇到麻煩,這些事件都包含視圖的el內。如果你是自己定義點擊,你的代碼變得不可管理。

所以,上你可以做什麼:

events!

可以定義1個視圖,牽着你的按鈕,點擊該按鈕時觸發一個事件,而需要處理一些代碼的其他意見當按下該按鈕時,不要直接綁定到按鈕上自己點擊,他們可以聽到該事件。

例如上的jsfiddle: http://jsfiddle.net/saelfaer/Qck5w/2/

它的要點在代碼在這裏:

// an event aggregator object to trigger and bind to 
var events = _.extend({}, Backbone.Events), 

// two views that talk to each other trough the event aggregator 
var myButtonView = Backbone.View.extend({ 
    // first view binds a click event to the button 
    events: { 
     "click a" : "myClickEvent" 
    }, 
    initialize: function(){ 
     _.bindAll(this, "render"); 
     this.render(); 
    }, 
    render: function(){ 
     return this; 
    }, 
    // click event executes this function, which triggers a custom event on the events object. 
    myClickEvent: function(e){ 
     $(e.target).blur(); 
     events.trigger("sidebar:myCustomClickEvent"); 
     return false; 
    } 
}); 

var myPanelView = Backbone.View.extend({ 
    // second view binds to that event, and executes the custom click handler 
    initialize: function(){ 
     _.bindAll(this, "render", "myClickEventHandler"); 
     events.bind("sidebar:myCustomClickEvent", this.myClickEventHandler); 
     this.render(); 
    }, 
    render: function(){ 
     return this; 
    }, 
    // the click handler does some logic (appends div) when the event is raised. 
    myClickEventHandler: function(){ 
     var txt = $('<div/>').text("you just clicked the button. (bound in other view)"); 
     $(this.el).append(txt); 
    } 
}); 
相關問題