Created
September 19, 2014 04:44
-
-
Save Leko/f77e73ea1913d160392c to your computer and use it in GitHub Desktop.
jsのデータモデリング、イベントハンドリングを面白く
This file contains hidden or 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
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