我有骨幹視圖,將操作綁定到DOM中的元素。問題是在調用事件時DOM元素還沒有被渲染。我的代碼如下所示:如何在骨幹初始化函數後將事件綁定到DOM?
// Change the focus to a full goal view
var GoalFullView = Backbone.View.extend({
// Bind the goal full view
el: $("#main"),
// Events for making changes to the goal
events: {
"keypress #goal-update": "createOnEnter",
},
// Cache the template for the goal full view
template: _.template($("#goal-full-template").html()),
// Render the goal full and all of its goal updates
initialize: function() {
this.render();
this.collection = new GoalUpdateList;
this.collection.bind('add', this.addOne, this);
this.collection.bind('reset', this.addAll, this);
this.collection.fetch();
},
正如你所看到的,事件綁定,是因爲它沒有被渲染它無法找到的DOM元素初始化之前發生。我怎樣才能延遲事件綁定,直到初始化後?
編輯1: 嗯,我做了控制檯日誌,和它打印出來的東西上一個按鍵,但我在我的Chrome的開發者控制檯收到此消息:
Uncaught TypeError: Cannot call method 'apply' of undefined
這是什麼意思?
只是綁定在初始化函數的事件。或使用委派。即將事件綁定到父元素,並在事件回調中測試哪個元素觸發了該事件。 – mpm 2012-04-03 08:35:47
我想我一直在使用這種方法,而且我沒有任何問題。讓我檢查一下。 – fguillen 2012-04-03 08:56:29
我不記得名爲'keypress'的事件,但我記得'keyup'。這可能是問題嗎? (順便說一句,愛你的用戶名:) – 2012-04-03 13:08:05