Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone: How to bind arguments for listenTo-callback?

Is it possible to bind function arguments for listenTo callback?

I've till now added a wrapper methods 'myHandler' which I would like to get rid of:

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

What I want to do is something like:

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);
}
like image 282
Fdr Avatar asked Dec 26 '22 04:12

Fdr


1 Answers

listenTo is accepting only 3 arguments. If you need to bind function to some object then cross-browser way to do this is using underscore _.bind function:

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

However it's mostly not needed as object you are calling listenTo on is the default context. To read more see these github issues:

  • https://github.com/documentcloud/backbone/issues/1946
  • https://github.com/documentcloud/backbone/issues/2015
like image 112
Adam Chwedyk Avatar answered Jan 05 '23 13:01

Adam Chwedyk