Skip to content

Instantly share code, notes, and snippets.

@aalavandhan
Created November 26, 2014 16:55
Show Gist options
  • Save aalavandhan/1a75c2e3120c6ccf5ba1 to your computer and use it in GitHub Desktop.
Save aalavandhan/1a75c2e3120c6ccf5ba1 to your computer and use it in GitHub Desktop.
$resource for Jquery - WIP
"/api/v1/resources/:resource_id"
"/api/v1/master/:master_id/resources/:id"
{
master_id: "master_id",
resource_id: "resource_id",
}
var Resource = function(url, map){
return function(object){
var instance = object || {};
var resource_url = _.reduce(map, function(memo, v, k){
return memo.replace(new RegExp(":"+k), object[v]);
}, url);
instance.$index = function(){
return $.get(resource_url + "?" + $.param(instance))
};
instance.$create = function(){
return $.post(resource_url, $.param(instance))
};
instance.$show = function(){
return $.get(resource_url + "?" + $.param(instance))
};
instance.$update = function(){
return $.put(resource_url, $.param(instance))
};
instance.$delete = function(){
return $.delete(resource_url, $.param(instance))
};
return instance;
};
};
kd.data.Question = new Resource("/api/test/:test_id/questions/:id", { id: "id", test: "test_id" });
kd.data.Test = new Resource("/api/test/:id", { id: "id" });
var t = new Test({ id: 5 });
t.$show().done(doSomething);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment