Skip to content

Instantly share code, notes, and snippets.

@Leko
Created September 19, 2014 04:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Leko/f77e73ea1913d160392c to your computer and use it in GitHub Desktop.
Save Leko/f77e73ea1913d160392c to your computer and use it in GitHub Desktop.
jsのデータモデリング、イベントハンドリングを面白く
var each = function(obj, callback) {
for(var p in obj) {
if(!obj.hasOwnProperty(p)) continue;
callback(p, obj[p]);
}
};
var Model = (function() {
function Model(params) {
each(params, function(prop, value) {
this[prop] = value;
}.bind(this));
}
Model.extend = function(defines) {
var cls = function() {};
cls.prototype.scheme = {};
each(defines.scheme, function(prop, value) {
cls.prototype.scheme[prop] = value;
Object.defineProperty(cls.prototype, prop, {
get: function() {
return this.scheme[prop];
},
set: function(val) {
var old = this.scheme[prop];
if(old !== val) {
console.log('change: ' + prop + ' = ' + val + ', old = ' + old);
}
this.scheme[prop] = val;
}
});
});
console.log(cls.prototype.scheme);
return cls;
};
return Model;
}());
var Human = Model.extend({
scheme: {
id: -1,
name: 'John Smith',
age: 21,
sex: 'male'
}
});
var h = new Human();
h.id = 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment