Last active
December 13, 2015 17:19
-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} | |
}) | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.