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

到目前为止,我想摆脱一个包装器方法“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);
}

最佳答案

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

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

但是,由于您要在其上调用listenTo的对象是默认上下文,因此通常不需要它。要了解更多信息,请参见以下github问题:
  • https://github.com/documentcloud/backbone/issues/1946
  • https://github.com/documentcloud/backbone/issues/2015
  • 07-28 11:21