Skip to content

Instantly share code, notes, and snippets.

@schovi
Last active December 14, 2015 06:18
Show Gist options
  • Save schovi/5041272 to your computer and use it in GitHub Desktop.
Save schovi/5041272 to your computer and use it in GitHub Desktop.
CanJS custom Api
// All calls reponses are converted into model instances or attributes are applied to current instance
var Api = can.Model('Api', {
callEndpoint: function(url) {
var ajax = this._ajax({}, url).call(this),
def = new can.Deferred(),
promise = def.promise(),
self = this;
promise.abort = ajax.abort
ajax
.done(function(data, status, xhr) {
def.resolveWith(self, [self._getModelsFromResponse(data), status, xhr])
})
.fail(function() {
def.rejectWith(self, arguments)
})
return promise;
},
_getModelsFromResponse: function(response) {
if(can.isArray(response)) {
return this.models(response)
}
return response
}
},{
_getModelFromResponse: function(response) {
var data;
if(can.isPlainObject(response)) {
this.attr(response)
return this
}
return response
},
callEndpoint: function(url) {
var ajax = this.constructor._ajax({}, url).call(this),
def = new can.Deferred(),
promise = def.promise(),
self = this;
promise.abort = ajax.abort
ajax
.done(function(data, status, xhr) {
def.resolveWith(self, [self._getModelFromResponse(data), status, xhr])
})
.fail(function() {
def.rejectWith(self, arguments)
})
return promise;
}
})
Api('User', {
findAll: "GET /users",
findOne: "GET /users/{id}",
// Not native calling
findAvailable: function() {
return this.callEndpoint("GET /users/available")
},
// Not native calling
// Call which returns user with some special properties for html form or anything else
new: function() {
var newUser = new this(),
def = newUser.prepareNew();
def.done(function(user) {
user.editing()
})
return def
}
}, {
// Not native calling
prepareNew: function() {
return this.callEndpoint("GET /users/new")
},
editing: function() {
this.attr('editable', true)
this.bind('someProperty', this.proxy('somePropertyChanged'))
},
somethingChanged: function() {
console.log("someProperty changed!")
},
// Not native calling
makeAvailable: function() {
return this.callEndpoint("GET /users/{id}/make_available")
}
})
// All this calls returns deffered obj like ajax.
var onlyAvailableUsers = User.findAvailable()
var notAvailableUser = User.findOne({id:100}) // This one is not available :)
notAvailableUser.makeAvailable()
notAvailableUser.attr('editable') != false
User.new().done(function(newUser) {
newUser.attr('editable') == true
})
@pravin-d
Copy link

Hey there.. would it be possible to explain whats happening in the code?
U have functions that do the same thing in instance and static methods of API. Little confused there

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment