Skip to content

Instantly share code, notes, and snippets.

@zourtney
Created February 19, 2014 23:18
Show Gist options
  • Save zourtney/9103669 to your computer and use it in GitHub Desktop.
Save zourtney/9103669 to your computer and use it in GitHub Desktop.
/**
* Model class
*/
Model = function(url, attributes) {
this.url = url;
this.attributes = attributes;
};
Model.prototype = {
set: function(data) {
this.attributes = data;
},
fetch: function() {
return $.getJSON(this.url + '/' + this.attributes.id, this.set.bind(this));
},
save: function() {
return $.ajax({
type: 'PUT',
contentType: 'application/json',
url: this.url,
data: JSON.stringify(this.attributes),
success: this.set.bind(this)
});
}
};
/**
* Collection class
*/
Collection = function(url) {
this.url = url;
};
Collection.prototype = {
_expand: function(data) {
this.data = [];
for (var i = 0; i < data.length; i++) {
this.data.push(new Model(this.url, data[i]));
}
},
fetch: function() {
return $.getJSON(this.url, this._expand.bind(this))
},
_flatten: function() {
var ret = [];
for (var i = 0; i < this.data.length; i++) {
ret.push(this.data[i].attributes);
}
return ret;
},
save: function() {
return $.ajax({
type: 'PUT',
url: this.url,
contentType: 'application/json',
data: JSON.stringify(this._flatten),
success: this.set.bind(this)
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment