Skip to content

Instantly share code, notes, and snippets.

@ryu1kn
Created February 21, 2015 07:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryu1kn/289fe78c97e9e3497054 to your computer and use it in GitHub Desktop.
Save ryu1kn/289fe78c97e9e3497054 to your computer and use it in GitHub Desktop.
Enum on Sencha Touch (ExtJS as well?)
/**
* @abstract
* @class MyApp.EnumBase
*/
Ext.define('MyApp.EnumBase', {
inheritableStatics: {
/**
* @return {Array.<MyApp.EnumBase>}
*/
values: function () {
return this._items.map(function (item) {
return Ext.isString(item) ? this[item] :
Ext.isObject(item) ? this[item.name] : null;
}, this);
},
/**
* @private
* @type {Array.<Object|string>} if use Objects, make sure they have `name` propertes
*/
_items: [],
/**
* Must be called in override classes when right after they're defined
* @protected
*/
_initializeEnum: function () {
Ext.Array.each(this._items, function (item, index) {
if (Ext.isString(item)) {
this[item] = new this({index: index});
} else if (Ext.isObject(item) && item !== null) {
var tmpItem = Ext.clone(item);
delete tmpItem.name;
this[item.name] = new this(Ext.apply(tmpItem, {index: index}));
} else {
throw new Error('Enum item should be given as either an Object or a string');
}
}, this);
this.prototype.constructor = function () {
throw new Error('Items of enum can be generated only on declaration');
};
}
},
config: {
/**
* @cfg {number}
*/
index: -1
},
constructor: function (config) {
this.initConfig(config);
}
});
/**
* @class MyApp.Season
*/
Ext.define('MyApp.Season', {
extend: 'MyApp.EnumBase',
requires: ['MyApp.EnumBase'],
statics: {
/**
* @private
* @type {Array.<Object|string>}
*/
_items: [{
name : 'SPRING',
bestFor: 'hiking'
}, {
name : 'SUMMER',
bestFor: 'swimming'
}, {
name : 'AUTUMN',
bestFor: 'playing tennis'
}, {
name : 'WINTER',
bestFor: 'skiing'
}]
},
config: {
/**
* @cfg {string}
*/
bestFor: ''
}
}, function () {
// Any ideas to do it in the super class?
this._initializeEnum();
});
// Test
MyApp.Season.values() // => [Class, Class, Class, Class]
MyApp.Season.values()[3] === MyApp.Season.WINTER // => true
MyApp.Season.WINTER instanceof MyApp.Season // => true
MyApp.Season.WINTER.getBestFor() // => "skiing"
MyApp.Season.WINTER.getIndex() // => 3
Ext.create('MyApp.Season', {name: 'foo'}) // => Uncaught Error: Items of enum can be generated only on declaration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment