W3cubDocs

/Marionette.js 2

Marionette.Behaviors

'Marionette.Behaviors' is a utility class that takes care of gluing your Behavior instances to their given View. The most important thing to understand when using this class is that you MUST override the class level behaviorsLookup method or set the option behaviorClass for things to work properly.

Documentation Index

API

There are two class level methods that you can override on the Behaviors class. The rest of the class is tied to under the hood implementation details of Views.

behaviorsLookup

This method defines where your Behavior classes are stored. A simple implementation might look something like this.

Marionette.Behaviors.behaviorsLookup = function() {
    return window.Behaviors;
}

By default the Behaviors are looked up by their key value in a given View's behavior hash.

In this sample (using the default getBehaviorClass implementation) your code will expect the following Behaviors to be present in window.Behaviors.DestroyWarn and window.Behaviors.ToolTip

var MyView = Marionette.ItemView.extend({
    behaviors: {
        DestroyWarn: {
            message: "you are destroying all your data is now gone!"
        },
        ToolTip: {
            text: "what a nice mouse you have"
        }
    }
});

getBehaviorClass

This method has a default implementation that is simple to override. It is responsible for the lookup of single Behavior from within the Behaviors.behaviorsLookup or elsewhere.

getBehaviorClass: function(options, key) {
    if (options.behaviorClass) {
        return options.behaviorClass;
    }

    return Behaviors.behaviorsLookup[key];
}

behaviorClass

This property lets you pass a class in for the Behavior to use (bypassing the normal key based lookup). This is nice to have when the Behavior is a dependency of the View in a module system like requirejs or browserify. Properties passed in this way will be used in getBehaviorClass.

define(['marionette', 'lib/tooltip'], function(Marionette, Tooltip) {
  var View = Marionette.ItemView.extend({
     behaviors: {
        Tooltip: {
          behaviorClass: Tooltip,
          message: "hello world"
        }
     }
  });
});

© 2016 Muted Solutions, LLC
Licensed under the MIT License.
https://marionettejs.com/docs/v2.4.7/marionette.behaviors.html