Javascript 具有自定义方法的主干视图

Javascript 具有自定义方法的主干视图,javascript,backbone.js,view,Javascript,Backbone.js,View,来自Java世界的我已经在视图中添加了自定义方法,但由于某些原因,我无法在视图中调用它们。看来Backbone.View.extend的行为与我期望的不一样 ... var TreeView = Backbone.View.extend({ el: '#org-tree', initialize: function() { eventBus.on("route:change", this.triggerFilterEvent); this.lis

来自Java世界的我已经在视图中添加了自定义方法,但由于某些原因,我无法在视图中调用它们。看来Backbone.View.extend的行为与我期望的不一样

  ...
  var TreeView = Backbone.View.extend({
    el: '#org-tree',

    initialize: function() {
      eventBus.on("route:change", this.triggerFilterEvent);
      this.listenTo(treeItems, 'sync', this.render);
      treeItems.fetch({
        reset: true
      });
    },

    render: function() {
      ...
    },

    foo: function() {
      console.log("foo");
    },

    triggerFilterEvent: function(name) {
      this.foo();
      ...
    }

  });
  ...
以下代码将导致
未捕获类型错误:对象没有方法“foo”
。 但是,我的另一个自定义方法
triggerFilterEvent
注册为eventHandler回调可以正常工作

1) 为什么呢?
2) 通过声明特定于TreeView的方法,我如何能够重用代码?

我认为问题在于
triggerFilterEvent
函数中的
这个
引用的是
事件总线
对象,而不是视图。请尝试以下方法:

eventBus.on("route:change", _.bind(this.triggerFilterEvent, this));

这是可用的方便下划线方法之一。更多信息

我认为问题在于
triggerFilterEvent
函数中的
引用的是
事件总线
对象,而不是视图。请尝试以下方法:

eventBus.on("route:change", _.bind(this.triggerFilterEvent, this));

这是可用的方便下划线方法之一。更多信息

我认为问题在于
triggerFilterEvent
函数中的
引用的是
事件总线
对象,而不是视图。请尝试以下方法:

eventBus.on("route:change", _.bind(this.triggerFilterEvent, this));

这是可用的方便下划线方法之一。更多信息

我认为问题在于
triggerFilterEvent
函数中的
引用的是
事件总线
对象,而不是视图。请尝试以下方法:

eventBus.on("route:change", _.bind(this.triggerFilterEvent, this));
这是可用的方便下划线方法之一。更多信息

请尝试

initialize: function() {
  var self = this;
  eventBus.on("route:change", self.triggerFilterEvent);
  this.listenTo(treeItems, 'sync', this.render);
  treeItems.fetch({
    reset: true
  });
}
试一试

initialize: function() {
  var self = this;
  eventBus.on("route:change", self.triggerFilterEvent);
  this.listenTo(treeItems, 'sync', this.render);
  treeItems.fetch({
    reset: true
  });
}
试一试

initialize: function() {
  var self = this;
  eventBus.on("route:change", self.triggerFilterEvent);
  this.listenTo(treeItems, 'sync', this.render);
  treeItems.fetch({
    reset: true
  });
}
试一试

initialize: function() {
  var self = this;
  eventBus.on("route:change", self.triggerFilterEvent);
  this.listenTo(treeItems, 'sync', this.render);
  treeItems.fetch({
    reset: true
  });
}

除非我弄错了,
bind
调用中的seoncd参数(
this
)仍然引用
eventBus
,因此它仍然不起作用。要使用
bind
您仍然首先需要根据我的回答保存对上下文的引用。对于我来说,绑定发生在初始化时,在该阶段
仍然引用视图。对我来说,这似乎是最优雅的解决方案。谢谢除非我弄错了,
bind
调用中的seoncd参数(
this
)仍然引用
eventBus
,因此它仍然不起作用。要使用
bind
您仍然首先需要根据我的回答保存对上下文的引用。对于我来说,绑定发生在初始化时,在该阶段
仍然引用视图。对我来说,这似乎是最优雅的解决方案。谢谢除非我弄错了,
bind
调用中的seoncd参数(
this
)仍然引用
eventBus
,因此它仍然不起作用。要使用
bind
您仍然首先需要根据我的回答保存对上下文的引用。对于我来说,绑定发生在初始化时,在该阶段
仍然引用视图。对我来说,这似乎是最优雅的解决方案。谢谢除非我弄错了,
bind
调用中的seoncd参数(
this
)仍然引用
eventBus
,因此它仍然不起作用。要使用
bind
您仍然首先需要根据我的回答保存对上下文的引用。对于我来说,绑定发生在初始化时,在该阶段
仍然引用视图。对我来说,这似乎是最优雅的解决方案。谢谢