I have a state machine for the major sections of the page:
App.States = Ember.StateManger.create({
foo: Ember.State.create({})
});
I have a view that needs to reset itself whenever the user enters the foo
state:
App.FooDisclosureView = Ember.View.extend({
didInsertElement: function() {
// whenever the button is pressed, toggle the disclosure:
var self = this;
this.$('button').click(function() {
self.get('disclosedContent').toggleProperty('isVisible');
});
},
reset: function() {
// close the disclosure if it's open
this.get('disclosedContent').set('isVisible', false);
}
});
The question is how to call FooDisclosureView#reset
when that state is entered.
App.FooDisclosureView = Ember.View.extend({
// as above...
resetOnEnterStateFoo: function() {
// if foo has child states, you can use a more intelligent matcher
if (App.getPath('States.currentState.name') === 'foo') {
this.reset();
}
}.observes('App.States.currentState.name')
});
Essentially the same as 1, but with a Controller.
App.fooController = Ember.Object.create({
active: false
});
App.States = Ember.StateManger.create({
foo: Ember.State.create({
enter: function() { App.setPath('fooController.active', true); },
exit: function() { App.setPath('fooController.active', false); }
})
});
App.FooDisclosureView = Ember.View.extend({
// as above...
resetOnEnterStateFoo: function() {
if (App.getPath('fooController.active')) {
this.reset();
}
}.observes('App.fooController.active')
});
This option requires changing Ember.StateManager
to emit events when states change. This could be a monkey-patch or, if generally useful, incorporated into the library.
App.FooDisclosureView = Ember.View.extend({
init: function() {
Ember.addListener(
App.States,
'stateChange',
this,
this.resetOnEnterStateFoo
);
},
resetOnEnterStateFoo: function(newState, oldState) {
if (newState.get('name') === 'foo') { this.reset(); }
},
// as above...
});
There are a few things I don't like about ViewStates:
view
property when you create the state. Since states can't be added to a StateManager after it's built, that means we need a whole bunch of view code in our states code.