-
-
Save daifu/3072522 to your computer and use it in GitHub Desktop.
orm.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
if (typeof Object.create !== "function") | |
Object.create = function(o) { | |
function F() {} | |
F.prototype = o; | |
return new F(); | |
}; | |
var Model = { | |
init: function(){ }, | |
prototype: { | |
init: function(){} | |
}, | |
create: function(){ | |
var object = Object.create(this); | |
object.parent = this; | |
object.init.apply(object, arguments); | |
return object; | |
}, | |
inst: function(){ | |
var instance = Object.create(this.prototype); | |
instance.parent = this; | |
instance.init.apply(instance, arguments); | |
return instance; | |
}, | |
extend: function(o){ | |
jQuery.extend(this, o); | |
}, | |
include: function(o){ | |
jQuery.extend(this.prototype, o); | |
} | |
}; | |
Model.proxy = Model.prototype.proxy = function(func){ | |
var thisObject = this; | |
return(function(){ | |
return func.apply(thisObject, arguments); | |
}); | |
}; | |
Model.extend({ | |
init: function(){ | |
this.records = {}; | |
this.attributes = []; | |
}, | |
find: function(id){ | |
var record = this.records[id]; | |
if ( !record ) throw("Unknown record"); | |
return record.dup(); | |
}, | |
populate: function(values){ | |
// Reset model & records | |
this.init(); | |
for (var i=0, il = values.length; i < il; i++) { | |
var record = this.inst(values[i]); | |
record.newRecord = false; | |
this.records[record.id] = record; | |
} | |
} | |
}); | |
Model.include({ | |
newRecord: true, | |
init: function(atts){ | |
if (atts) this.load(atts); | |
}, | |
load: function(attributes){ | |
for(var name in attributes) | |
this[name] = attributes[name]; | |
}, | |
attributes: function(){ | |
var result = {}; | |
for(var i in this.parent.attributes) { | |
var attr = this.parent.attributes[i]; | |
result[attr] = this[attr]; | |
} | |
result.id = this.id; | |
return result; | |
}, | |
create: function(){ | |
this.newRecord = false; | |
this.parent.records[this.id] = this.dup(); | |
}, | |
update: function(){ | |
this.parent.records[this.id] = this.dup(); | |
}, | |
save: function(){ | |
this.newRecord ? this.create() : this.update(); | |
}, | |
destroy: function(){ | |
delete this.parent.records[this.id]; | |
}, | |
dup: function(){ | |
return jQuery.extend(true, {}, this); | |
}, | |
toJSON: function(){ | |
return(JSON.stringify(this.attributes())); | |
} | |
}); | |
var Asset = Model.create("Asset"); | |
var Person = Model.create("Person"); | |
var asset = Asset.inst({id: 1}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment