Enum Factory
var mapApp = ...
myApp.factory('Enumerate', function () {
return function (list, fnc) {
var Enumerate = function (ctx) {
if (angular.isObject(ctx)) {
angular.forEach(ctx, function (val, key) {
this[key] = val;
}, this);
} else if (angular.isString(ctx)) {
this.name = ctx;
} else {
throw new Error('incorrect arguments.');
}
};
Enumerate.values = [];
Enumerate.valueOf = function (ctx) {
var obj = null;
angular.forEach(Enumerate.values, function (item) {
if (item.name === ctx) {
obj = item;
return false;
}
});
if (!obj) {
obj = new Enumerate(ctx);
Enumerate.values.push(obj);
}
return obj;
}
Enumerate.prototype.toString = function () {
return this.name;
};
fnc && angular.forEach(fnc, function (val, key) {
Enumerate.prototype[key] = val;
});
angular.forEach(list, function (item) {
Enumerate[
angular.isObject(item)
? item.name
: item
] = Enumerate.valueOf(item);
});
return Enumerate;
};
});
Using
myApp..factory('StandardColumn', [
'Enumerate',
function (Enumerate) {
var StandardColumn = function () {
};
/* define enum */
StandardColumn.Format = Enumerate([
{name: 'STRING', description: 'ตัวหนังสือ'},
{name: 'NUMBER', description: 'ตัวเลข'},
{name: 'STUDENT', description: 'นักเรียน'}
]);
StandardColumn.Format.fromDescription = function (desc) {
var obj = null;
angular.forEach(StandardColumn.Format.values, function (item) {
if (item.description === desc) {
obj = item;
return false;
}
})
return obj;
};
StandardColumn.Operation = Enumerate([
'SUM',
'AVERAGE'
]);
StandardColumn.prototype = {
id: null,
name: null,
sequence: 1,
format: StandardColumn.Format.STRING,
operation: null,
operateWith: null
};
return StandardColumn;
}
]);
ไม่มีความคิดเห็น:
แสดงความคิดเห็น