Skip to content

Instantly share code, notes, and snippets.

@publickeating
Last active December 13, 2015 17:19
Show Gist options
  • Save publickeating/4946794 to your computer and use it in GitHub Desktop.
Save publickeating/4946794 to your computer and use it in GitHub Desktop.
A custom view that manages its state using SC.StatechartManager instead of internal flags. This is a simple view that only needs to toggle an active property when the mouse is over it. However, as simple as this requirement is, we can see that it benefits from using a statechart because the isEnabled value affects the behaviour. Imagine if there…
/**
* A view that adds an 'active' class when the mouse is over it.
*/
MyApp.MyView = SC.View.extend(SC.StatechartManager, {
/** @private */
displayProperties: ['isActive', 'isEnabled'],
/**
Whether the view is active or not.
@property Boolean
@default false
*/
isActive: false,
/** @private The default value is 'owner', which gets set by SC.View to the parentView, but we want owner to default to 'this'. */
statechartOwnerKey: 'statechartOwner',
/** @private */
render: function (context) {
context.setClass({
'active': this.get('isActive')
});
},
/** @private The statechart. */
rootState: SC.State.design({
initialSubstate: 'idleState',
// Idle state.
idleState: SC.State.design({
mouseEntered: function (evt) {
var view = this.get('owner');
if (view.get('isEnabled')) {
this.gotoState('mouseOverState');
return true;
}
}
}),
// Mouse over state.
mouseOverState: SC.State.design({
enterState: function () {
var view = this.get('owner');
view.set('isActive', true);
},
exitState: function () {
var view = this.get('owner');
view.set('isActive', false);
},
// Start observing isEnabled while in this state.
isEnabledDidChange: function () {
var view = this.get('owner');
view.set('isActive', view.get('isEnabled'));
}.stateObserves('.owner.isEnabled'),
mouseExited: function (evt) {
this.gotoState('idleState');
return true;
}
})
})
});
@lukemelia
Copy link

I think this can be a really useful approach. Flame.js, a widget library for Ember, has some interesting examples of this approach, too. e.g.: https://github.com/flamejs/flame.js/blob/master/views/list_view.js

@dcporter
Copy link

This is awesome. I think the "statechartOwnerKey" thing could use a little more explanation (I'm not familiar with the owner concept as it applies to states), for right now I'm just copy/pasting it blind.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment