2013-04-14 56 views
0

我有如下:骨幹的layoutManager delegateEvents不工作

Views.Parent = Backbone.View.extend({ 
    template: "parent", 
    initialize: function() { 
     this.render(); 
    }, 
    beforeRender: function() { 
     this.setView(".foo", new Views.Child({ 
      model: this.model 
     }); 
    }, 
    afterRender: function() { 
     this.$el.html(Handlebars.compile(this.$el.html()).call(this, this.model.attributes)); 
     var foo = this.getView(".foo"); 
     foo.delegateEvents(); 
    } 
}); 

Views.Child = Backbone.View.extend({ 
    template: "child", 
    events: { 
     "click input": "inputClick" 
    }, 
    initialize: function() { 
     this.listenTo(this.model, "change", this.render); 
    }, 
    inputClick: function() { 
     console.info("Input Clicked"); 
    }, 
    afterRender: function() { 
     this.$el.html(Handlebars.compile(this.$el.html()).call(this, this.model.attributes)); 
     var foo = this.getView(".foo"); 
     foo.delegateEvents(); 
    } 
}); 

Views.Child事件不會開火。該視圖是絕對找到的,並且foo.events返回正確的事件。我嘗試過多種插入我的子視圖的方法,delegateEvents只是沒有做到這一點。

有沒有其他人跑到這,並可以提供任何見解?

我應該提到我在子視圖中使用了events屬性和this.listenTo。他們都沒有被解僱。

編輯:父被添加到另一個視圖,例如: this.$el.append(parentView.$el);

parentViewViews.Parent實例化的對象。

+0

Views.Child的外觀如何? – domino

+0

我更新了帖子。這是我爲了清晰起見而實際運行的代碼的簡化版本。 – aef

+0

'this.listenTo(model,「change」,this.render);''「model」'不應該是字符串 – domino

回答

1

當您在中致電this.$el.html時,您將覆蓋當前的HTML視圖(以及每個綁定的事件/子視圖)。因此,您將刪除您在beforeRender中設置的子視圖。

這就是爲什麼你沒有事件發生。

我想提供更多關於如何組織代碼的信息......但我無法理解你在afterRender中試圖做什麼,這是毫無意義的。編譯fetchrender配置選項中的所有模板代碼,而不是afterRender

快速注意:
beforeRender:你設置子視圖
afterRender:在您綁定的事件或啓動jQuery插件,等你不應該在這裏接觸到DOM。

+0

你釘了它,我錯誤地使用了layoutmanager。我能夠將句柄重構爲LayoutManager.fetch並使用serialize傳遞上下文。十分感謝你的幫助。 – aef

+0

過得很愉快,祝你好運。順便說一句,如果你想討論更多的概念,隨意跳入#backbone-boilerplate IRC頻道。 –