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

问题描述 投票:0回答:1

我在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)上起作用?

javascript backbone.js
1个回答
0
投票

我已经解决了所有我需要在初始化时绑定主干对象的问题。

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关键字在自定义函数变量内调用主干对象。

© www.soinside.com 2019 - 2024. All rights reserved.