BackboneJS: this.$el 在其他键值函数上未定义 (Backbone.View)

BackboneJS: this.$el undefined on other key value function (Backbone.View)

我在 JavaScript 中有这样的代码:

var addModalView = Backbone.View.extend({
      tagName:"div",
      el:$("#addemployee"),
      showbutton:$("#addemployee_button"),
      showbutton_click:function(e) {
          this.$el.modal("show"); // this.$el is undefined and not working
      },
      initialize:function() {
        this.showbutton.on("click", this.showbutton_click);
        this.$el.modal("show"); // this.$el is defined and working
      }
  });
myaddModalView = new addModalView();

为什么 this.$el 已定义并正在初始化而不是其他键索引 (showbutton_click)?

我已经解决了这个问题,我只需要在初始化时绑定 backbone 对象。

var addModalView = Backbone.View.extend({
      tagName:"div",
      el:$("#addemployee"),
      showbutton:$("#addemployee_button"),
      showbutton_click:function(e) {
          this.$el.modal("show"); // this.$el is now defined and working
      },
      initialize:function() {
        this.showbutton.on("click", this.showbutton_click);
        _.bindAll(this, "showbutton_click"); // bind it first on showbutton_click
        this.$el.modal("show"); // this.$el is defined and working
      }
  });
myaddModalView = new addModalView();

此绑定代码是解决方案,应添加到 initialize_.bindAll(this, "showbutton_click"); 以便您可以使用 this 在自定义函数变量中调用 backbone 对象关键字。

正确的实现应该像这样使用 events 散列。

var addModalView = Backbone.View.extend({
  el: $("#addemployee"), // should be avoided if possible
  events: {
    'click #addemployee_button': 'showbutton_click'
  },
  initialize: function() {
    this.$el.modal("show");
  },
  showbutton_click: function(e) {
    this.$el.modal("show");
  },
});

myaddModalView = new addModalView();

如果由于某种原因 #addemployee_button 不在 "#addemployee" 内,那么事件绑定应该发生在实际包含它的视图中。