Can I call behaviors methods directly without eventproxy?

142 views Asked by At

I'm searching for alternative ways to call a method defined in Marionette's behaviors from inside a view.

For sure there is the eventproxy but maybe it's more intuitive to call the method directly like:

view.behaviorsMethod();

I could assign it like:

view.method = behavior.method;

I could check for reassignment because it'll maybe lead to unexpected results for others:

view.method = (view.method !== undefined ? view.method : behavior.method);

But this doesn't seem to be an elegant way.

1

There are 1 answers

1
nikhil mehta On BEST ANSWER

The answer to your question is you can not directly do so, but there is always a way. you can do it using _.invoke(this._behaviors, 'yourMethodName') but I will discourage using it since

  1. _behaviors is a private variable of the Marionette.View class and it's name can be changed or it can be dropped in upcoming versions

  2. You will have to set context for the method as _.invoke will not set the context of the method to proper this.

if you can set the context properly then this will work for you.

as suggested by @ThePaxBisonica in comment I will suggest you to go with a mixin pattern from which you can extend both your behavior and view and you will not have to set any context and do not have to worry about the _behavior private variable

as

var mixin = {
    behaviorMethodWhichYouWantToCallFromView: function(){
           alert("mixin method");
    }
}

var behavior = mn.behavior.extend(_.extend(mixin, {
    //actual behavior code remove the method as behavior will get it from mixin
}))

var view = mn.view.extend(_.extend(mixin, {
    //actual view code remove the method as behavior will get it from mixin
}))

Hope it helps. I know this is bit long approach.