Created
April 9, 2015 17:23
-
-
Save iorlas/cf6f31b74e97e771c62f to your computer and use it in GitHub Desktop.
This file contains 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
class BaseModel | |
url: null | |
http: null | |
promise: null | |
constructor: (data={}, @params, extra)-> | |
_.extend @, extra if extra | |
@processData data | |
@get: (id, params, extra) -> | |
object = new @prototype.constructor id: id, params, extra | |
object.reload() | |
@getList: (params, extra) -> | |
CollectionClass = @prototype.collection or SortableCollection | |
collection = new CollectionClass @, params, extra | |
collection.reload() | |
@createCollection: (data, params, extra) -> | |
CollectionClass = @prototype.collection or SortableCollection | |
collection = new CollectionClass @, params, extra | |
collection.processData(data) | |
reload: -> | |
@promise (success, failure) => | |
@isLoading = true | |
@http.get "#{@url}/#{@data.id}", | |
params: @params | |
.success (data) => | |
success @processData(data) | |
.catch failure | |
.finally => @isLoading = false | |
preprocessData: (data) -> data | |
processData: (data) -> | |
@data = @preprocessData data | |
@ | |
class @Model extends BaseModel | |
postData: (method, url, params) -> | |
@promise (success, failure) => | |
@errors = null | |
@isLoading = true | |
@http | |
method: method | |
url: url | |
params: params | |
data: @data | |
.success (data) => | |
success @processData(data) | |
.catch (res) => | |
@errors = res.data | |
.finally => @isLoading = false | |
save: -> | |
(if @data.id then @update else @create).apply @, arguments | |
@options: -> @prototype.options.apply @, arguments | |
options: -> | |
@promise (success, failure) => | |
@http | |
method: 'OPTIONS' | |
url: @url | |
.success success | |
.catch failure | |
create: (params) -> @postData 'POST', @url, params | |
update: (params) -> @postData 'PUT', "#{@url}/#{@data.id}", params | |
action: (method, name, params) -> | |
@promise (success, failure) => | |
@http _.extend({ | |
method: method | |
url: "#{@url}/#{@data.id}/#{name}" | |
}, params) | |
.success success | |
.catch failure |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment