如何在骨干中初始化函数后将事件绑定到DOM?

egi*_*dra 5 javascript backbone.js

我有骨干视图,将动作绑定到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();
    },
Run Code Online (Sandbox Code Playgroud)

如您所见,事件绑定发生在初始化之前,因此它无法定位DOM元素,因为它尚未呈现.如何在初始化之后延迟事件绑定?

编辑1:嗯,我做了一个控制台日志,它在按键上输出了一些东西,但是我在Chrome的开发者控制台中收到了这条消息:

Uncaught TypeError: Cannot call method 'apply' of undefined
Run Code Online (Sandbox Code Playgroud)

这是什么意思?

fgu*_*len 3

正如我所料,问题出在另一个地方。

\n\n

DOMevents绑定声明可以在 DOM 元素真正存在之前完成。

\n\n

我认为这个代码示例重现了您正在谈论的情况,并且 DOM 仍然event正确绑定。

\n\n
var View = Backbone.View.extend({\n  events: {\n    "click #link": "click"\n  },\n\n  click: function(){\n    console.log( "click event" );\n  },\n\n  render: function(){\n    this.$el.html( "<a href=\'#\' id=\'link\' onclick=\'return false\'>link</a>" );\n  }\n});\n\nnew View({ el: "body" }).render();\xe2\x80\x8b\n
Run Code Online (Sandbox Code Playgroud)\n\n

检查jsfiddle 示例代码

\n