Created
June 17, 2011 14:28
-
-
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.
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
(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