-
Notifications
You must be signed in to change notification settings - Fork 0
/
serialize_backbone_model.coffee
58 lines (46 loc) · 1.79 KB
/
serialize_backbone_model.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#
# Ref #740:
#
# overwrite save method of Backbome.Model to serialize request to avoid
# the requests are processed out of order on server
#
Backbone.Model.prototype.original_save = Backbone.Model.prototype.save
Backbone.Model.prototype.original_destroy = Backbone.Model.prototype.destroy
Backbone.Model.prototype.save = (key, val, options) ->
@_requestQueue = [] if !@_requestQueue
@_requestQueue.push {key:key, val:val, options:options}
attrs = @attributes
# Handle both `"key", value` and `{key: value}` -style arguments.
if (key == null || typeof key == 'undefined' || typeof key == 'object')
attrs = key
options = val
else
(attrs = {})[key] = val
options = {} if !options
# If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`.
return false if (attrs && (!options || !options.wait) && !@set(attrs, options))
@_saveCalled = true
if @_requestQueue.length > 1
return false
success = options.success
error = options.error
dequeue = () =>
param = _.last(@_requestQueue)
length = @_requestQueue.length
@_requestQueue = []
@save(param.key, param.val, param.options) if length > 1
options.success = (model, resp, options) ->
success(model, resp, options) if success
dequeue()
options.error = (model, resp, options) ->
error(model, resp, options) if error
dequeue()
# Set back `options` to `val` to handle `{key: value}` style
val = options if (key == null || typeof key == 'undefined' || typeof key == 'object')
@original_save(key, val, options)
Backbone.Model.prototype.destroy = (options) ->
if !@get('id') && @_saveCalled
# Ref #1090 delay destroy call if model doesn't have an id yet
@on 'change:id', () => @original_destroy(options) if @get('id')
else
@original_destroy(options)