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

m2xkgtsf  于 2022-11-10  发布在  其他
关注(0)|答案(2)|浏览(118)

我有一个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)上?

gcuhipw9

gcuhipw91#

正确的实现应该像这样使用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"内,那么事件绑定应该发生在实际包含它的任何视图中。

kqqjbcuj

kqqjbcuj2#

我已经解决了这个问题,我所需要的就是在初始化时绑定 Backbone.js 对象。

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.js 对象。

相关问题