4

是否可以为 listenTo 回调绑定函数参数?

到目前为止,我已经添加了一个包装方法“myHandler”,我想摆脱它:

// Basic marionette layout
var view = Marionette.Layout.extend({

initialize: function() {
    // wrapping view logic inside a custom object
    this.controller = new MyViewController(); 
},

// creates a sub view and adds event handlers
someFunc: function() {
    var subView = new MySubView();

    // HERE: how to bind args for callback?
    this.listenTo(subView, "myEvent", this.myHandler, this);
}, 

// this is a dummy wrapper that I want to remove
myHandler: function(e) {
    this.controller.handleIt(this, e);
},

我想做的是:

someFunc: function() {
    var subView = new MySubView();

    // here wrapIt binds 'this' as first argument for handleIt
    this.listenTo(subView, "myEvent",
        wrapIt(this.controller.handleIt, this), this);
}
4

4 回答 4

7

listenTo只接受 3 个参数。如果您需要将函数绑定到某个对象,那么跨浏览器的方法是使用下划线_.bind函数:

this.listenTo(subView, "myEvent", _.bind(this.myHandler, this))

但是,它通常不需要,因为您调用的对象listenTo是默认上下文。要阅读更多内容,请参阅这些 github 问题:

于 2013-05-01T14:19:55.400 回答
2

为什么不在listenTo 函数调用中使用一个函数?像这样:

// Basic marionette layout
var view = Marionette.Layout.extend({

  initialize: function() {
    // wrapping view logic inside a custom object
    this.controller = new MyViewController(); 
  },

  // creates a sub view and adds event handlers
  someFunc: function() {
    var subView = new MySubView();

    this.listenTo(subView, "myEvent", function (e) {
      this.controller.handleIt(this, e);
    }, this);
  }, 
于 2013-05-01T21:40:43.613 回答
1

Underscore是 Backbone 的硬依赖,这意味着您可以使用_.bind来设置上下文:

bind _.bind(function, object, [*arguments])
将函数绑定到对象,这意味着每当调用该函数时,this 的值就是该对象。或者,将参数传递给函数以预填充它们,也称为部分应用。

你的例子可以写成

someFunc: function() {
    var subView = new MySubView(),
        callback = _.bind(this.controller.handleIt, this);

    this.listenTo(subView, "myEvent", callback, this);
}

如果您希望上下文作为函数的第一个参数,请将其作为第三个参数添加到_.bind

someFunc: function() {
    var subView = new MySubView(),
        callback = _.bind(this.controller.handleIt, this, this);

    this.listenTo(subView, "myEvent", callback, this);
}
于 2013-04-30T09:39:44.270 回答
0

是的,您可以在 JQuery $.proxy(this.controller.handler, this) 中使用代理函数来做到这一点,请参阅此处的文档 http://api.jquery.com/jQuery.proxy/

于 2013-04-30T14:03:24.690 回答