Skip to content

Instantly share code, notes, and snippets.

@csaunders
Created June 17, 2011 14:28
Show Gist options
  • Save csaunders/1031521 to your computer and use it in GitHub Desktop.
Save csaunders/1031521 to your computer and use it in GitHub Desktop.
Ajax Prefixes and Find by ajax query if Spine.Model doesn't exist locally.
(function(Spine, $){
if( typeof Spine.Model.Ajax === "undefined") { throw "This plugin is really intended for use with Ajax driven models"; }
var Model = Spine.Model;
Model.extend({
find: function(id) {
record = this.records[id];
if( !record) {
var self = this;
self.ajaxPrefix = self.singletonPrefix();
$.ajax({
url: this.url + "/" + id,
dataType: "json",
success: function(data){
item = self.fromJSON(data);
self.records[item.id] = item;
self.ajaxPrefix = self.collectionPrefix();
self.trigger("ajax-find");
},
error: function(xhr, status, errorThrown){
throw "Unknown record";
}
});
return null
}
return record.clone();
},
singletonPrefix: function(){ return this.name.toLowerCase(); },
collectionPrefix: function(){ return this.name.toLowerCase() + "s"; }
});
Model.include({
persist: function(){
this.parent.ajaxPrefix = this.parent.singletonPrefix()
this.save();
this.parent.ajaxPrefix = this.parent.collectionPrefix();
}
});
})(Spine, Spine.$);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment