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...
});
I generally don't care for Option 1. It feels clunky given how clean states are. Option 2 feels most the like Ember, so would say it is a fine option. Options 3 feels more like pre-ember JS. I am a fan of custom events as they're great at decoupling. I like how this feels and wouldn't oppose it, but I do feel like this is basically the same functionality Ember offers us.