Skip to content

Instantly share code, notes, and snippets.

@jkappers
Last active August 29, 2015 14:09
Show Gist options
  • Save jkappers/593f68af1c5735a1663f to your computer and use it in GitHub Desktop.
Save jkappers/593f68af1c5735a1663f to your computer and use it in GitHub Desktop.
Organizing AJAX calls by using a very simple inheritance structure and jQuery extend.
function Model(){}
// Converts a hash or each hash of an array into an instance of the calling class.
Model.fromObject = function(obj){
if (obj && !$.isArray(obj)){
return $.extend(new this(), obj);
}
var collection = [];
for(var index in obj){ collection.push(this.fromObject(obj[index])); }
return collection;
}
// Get a copy of all model attributes and values.
Model.prototype.serialize = function(){
var obj = {};
for (var key in this) {
if (this.hasOwnProperty(key)) {
obj[key] = this[key]
}
}
return obj;
}
// Find a single user with an id of 1
// Change the name and email and save the changes.
User.find(1).then(function(user){
user.name = "Joshua";
user.email = "jkappers@kalkomey.com";
user.update();
});
// Define the model
function User() {}
// Mix Model class methods into the User model.
$.extend(User, Model);
// Prototypically inherit instance methods of Model
User.prototype = new Model();
// Get a list of all users.
User.all = function(){
return $.getJSON('/users')
.then(function(response){
return User.fromObject(response);
});
}
// Find a single user by id.
User.find = function(id) {
var url = '/users/' + id;
return $.getJSON(url)
.then(function(response){
return User.fromObject(response);
});
}
// Update a user
User.prototype.update = function() {
var url = '/user/' + this.id,
data = this.serialize();
return $.ajax({
url: url,
type: 'PUT',
data: data
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment