Search code examples
javascriptbackbone.jsmarionettebackbone-viewsbehavior

Marionette Behaviors: Add dynamic options


How can I add a behavior to my view with a variable as an option? In my case, the variable I want to use is an option of the view, but, when I tried this:

behaviors: {
    prodMessage: {
        profile: this.options.userdata.attributes._userid
    }
},

I get:

Uncaught TypeError: Cannot read property 'attributes' of undefined

I think that is because this take place in the construction rather than the initilization.

So, do you have any workaround to achieve this?


Solution

  • The code in your version gets executed during application loading. So this does not actually point to the view instance, but probably to window object. To have this point to the view, you need defer the specification of the behaviors, so that it get executed when the view instance is constructed:

    ``

    behaviors: function() {
      return {
        prodMessage: {
          profile: this.options.userdata.attributes._userid
        }
      };
    }
    

    ``

    See this codepen for full version.


    Alternative option is to have the behavior access the view through this.view:

    prodMessage = Marionette.Behavior.extend({
      onShow: function() {
        alert(this.view.options.userdata.attributes._userid);
      }
    });