(function(){
var Model = {
inherited: function(){},
created: function(){},
prototype: {
init: function(){}
},
create: function(){
var object = Object.create(this);
object.parent = this;
object.fn = object.prototype;
object.created();
this.inherited(object);
return object;
},
init: function(){
var instance = Object.create(this.prototype);
instance.parent = this;
instance.init.apply(instance, arguments);
return instance;
},
extend: function(o){
var extended = o.extended;
jQuery.extend(this, o);
if(extended) extended(this);
},
include: function(o){
var included = o.included;
jQuery.extend(this.prototype, o);
if(included) included(this);
}
};
Model.records ={};
Model.extend({
find: function(id){
return this.records[id];
}
});
Model.include({
newRecord: true,
create: function(){
this.newRecord = false;
this.parent.records[this.id] = this;
},
destroy: function(){
delete this.parent.records[this.id];
},
update: function(){
this.parent.records[this.id] = this;
},
save: function(){
this.newRecord ? this.create() : this.update();
},
init: function(atts){
if(atts) this.load(atts);
},
load: function(attributes){
for(var name in attributes){
this[name] = attributes[name];
};
}
});
var Asset = Model.create();
var asset = Asset.init();
asset.name = 'おなじ';
asset.id = 1;
asset.save();
var asset2 = Asset.init();
asset2.name = 'でもちがう';
asset2.id = 2;
asset2.save();
console.log(Asset.find(1).name);
console.log(Asset.find(2).name);
asset2.destroy();
console.log(Asset.find(1));
console.log(Asset.find(2)); // => undefined
}());
External resources loaded into this fiddle: