2013-04-30 29 views
4

是否有可能爲listenTo回調綁定函數參數?Backbone:如何綁定listenTo-callback的參數?

我到現在增加了一個包裝方法「將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); 
} 
+0

什麼是'this.controller.handleIt'? – 2013-04-30 07:17:08

+0

@ Qantas94Heavy這是一個封裝視圖邏輯的FSM:[javascript-state-machine](https://github.com/jakesgordon/javascript-state-machine) – Fdr 2013-04-30 07:25:36

+0

這些答案都有幫助嗎? – martin308 2013-10-09 23:16:27

回答

1

下劃線爲骨幹硬依賴,這意味着你可以使用_.bind設置上下文:

綁定 _.bind(函數,對象,[*自變量])
將函數綁定到一個對象,這意味着無論何時調用該函數,該值都將是該對象的 。或者,將參數傳遞給函數 預先填充它們,也稱爲部分應用程序。

如果你想在上下文中的第一個參數的功能,它作爲第三個參數添加到_.bind

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

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

你舉的例子可以寫成

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

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

是的,你可以在jQuery中使用代理函數做這件事 $ .proxy(this.controller.handler,this) 在這裏查看文檔 http://api.jquery.com/jQuery.proxy/

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); 
    }, 
+1

這是一個過時的解決方案,listenTo方法的第四個參數已從骨幹核心中刪除:https://github.com/jashkenas/backbone/issues/2015您可以使用_.bind() – Mironor 2014-06-27 16:28:43