How to use Backbone.StateManager?

I am trying to learn Backbone.StateManager but could not find much material on this. I went through the documentation , but there is no simple example of its use.

I made such an example

(function($) { var UserInputView = Backbone.View.extend({ states: { foo: { enter: function () { alert('hi'); return console.log('enter bar'); }, exit: function () { alert('hi'); return console.log('exit foo'); }, transitions: { transitions: { 'onBeforeExitTo:anotherState': function () { alert('hi'); }, 'onExitTo:anotherState': function () { alert('hi'); }, 'onBeforeEnterFrom:anotherState': function () { alert('hi'); }, 'onEnterFrom:anotherState': function () { alert('hi'); } } } }, bar: { enter: function () { alert('hi'); return console.log('enter bar'); }, exit: function () { alert('hi'); return console.log('exit bar'); }, } }, initialize: function () { var statemanager; alert('intialized'); console.log(this.states); statemanager = Backbone.StateManager.addStateManager(this.states); return statemanager; }, render: function () { alert('render'); } }); var user = new UserInputView(); })(jQuery); 

In all of this code, only the intialization function works. The rest of the code does not work. Please direct

+4
source share
1 answer

Basically, your code skips the state change and the correct target for Backbone.StateManager.addStateManager . As stated in the documentation, use Backbone.StateManager with objects

StateManager provides an easy way to seamlessly add a StateManager to any object. StateManager.addStateManager accepts the target and an optional set of options, reads in any states defined on the target, and creates a new StateManager. It also sets up a number of methods for the target, including triggerState , getCurrentState , and a link to the StateManager in target.stateManager .

which means that the target for Backbone.StateManager.addStateManager should be your instance of the object, and you can start changing state using model.triggerState . For instance:

 var UserInputView = Backbone.View.extend({ states: { // your states }, initialize: function () { var statemanager; statemanager = Backbone.StateManager.addStateManager(this); } }); var user = new UserInputView(); user.triggerState('foo'); 

Demo based on your code, visualize some state manipulations

+1
source

All Articles