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);
}
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With