Created
June 24, 2009 05:27
-
-
Save benschwarz/135032 to your computer and use it in GitHub Desktop.
This file contains 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
// Found on my desktop from early 07' | |
// JSON ActiveResource - REST Implementation | |
/* | |
Example of use. | |
new Model('User'); | |
var myUser = User.find(12); | |
myUser.name = 'Benjamin'; | |
myUser.save; | |
Code structure: | |
Users' methods | |
find | |
save | |
create | |
update_attribute | |
new | |
destroy | |
+ its methods | |
Transport | |
save | |
destroy | |
new | |
Extended use | |
new Model('User', {controller: 'accounts'}); | |
new Model('User', {resource: 'http://beast.caboo.se'}); | |
new Model('User', {resource: 'http://beast.caboo.se', controller: 'accounts'}); | |
var myAsset = Asset.find(201); | |
myAsset.tags.push('value'); // need to figure out associations | |
myAsset.save; | |
*/ | |
// Dispatch our model instance to its own object and methods | |
var Model = function (name, options) { this.init(name, options); }; | |
Model.prototype = { init: function (name, options) { eval(name + ' = new ModelInstance(name, options || {});'); }}; | |
// Our model instance | |
var ModelInstance = function (name, options) { this._init(name, options); }; | |
ModelInstance.prototype = { | |
_init: function (name, options) { | |
var options = options || {}; | |
this._resource = options.resource || ''; | |
this._controller = options.controller || name.toLowerCase() + 's'; | |
}, | |
new: function (attribs) { | |
// Load from server and push in attributes (optional) | |
}, | |
find: function (id) { | |
// Return record | |
$.get(this._singular_url(id), function (xhr) { | |
return xhr; | |
}, 'json'); | |
}, | |
create: function (attribs) { | |
// Push in attributes (optional) POST to server, return object | |
// Status 201 for succss | |
}, | |
update: function (attribs) { | |
// Push in attributes (optional) PUT to server, return object | |
// Status 200 for success | |
}, | |
save: function () { | |
// Save object to server | |
if(this.new_record()) { | |
return this.create(); | |
} else { | |
return this.update(); | |
} | |
}, | |
destroy: function (id) { | |
var id = id || this.id; | |
var response = $.post(this._singular_url(id), {_method: "delete"}).responseText; | |
if(response.status == 200) { | |
this.id = null; | |
return this; | |
} else { | |
return false; | |
} | |
}, | |
new_record: function () { return !(this.id) }, | |
_singular_url: function (id) { return this._resource + '/' + this._controller + '/' + (id || this.id) + '.js'; }, | |
_plural_url: function () { return this._resource + '/' + this._controller + '.js'; } | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment