-
Notifications
You must be signed in to change notification settings - Fork 20
/
backbone-tastypie.js
104 lines (83 loc) · 3.16 KB
/
backbone-tastypie.js
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
(function($, _, Backbone) {
Backbone.Tastypie = {
defaultLimit: 20
};
Backbone.Tastypie.Model = Backbone.Model.extend({
idAttribute: 'resource_uri',
url: function() {
var url = getValue(this, 'urlRoot') || getValue(this.collection, 'urlRoot') || urlError();
if (this.isNew())
return url;
return this.get('resource_uri');
},
_getId: function() {
if (this.has('id'))
return this.get('id');
return _.chain(this.get('resource_uri').split('/')).compact().last().value();
}
});
Backbone.Tastypie.Collection = Backbone.Collection.extend({
constructor: function(models, options) {
Backbone.Collection.prototype.constructor.apply(this, arguments);
this.meta = {};
this.filters = {
limit: Backbone.Tastypie.defaultLimit,
offset: 0
};
if (options && options.filters)
_.extend(this.filters, options.filters);
},
url: function(models) {
var url = this.urlRoot;
if (models) {
var ids = _.map(models, function(model) {
return model._getId();
});
url += 'set/' + ids.join(';') + '/';
}
return url + this._getQueryString();
},
parse: function(response) {
if (response && response.meta)
this.meta = response.meta;
return response && response.objects;
},
fetchNext: function(options) {
options = options || {};
options.add = true;
this.filters.limit = this.meta.limit;
this.filters.offset = this.meta.offset + this.meta.limit;
if (this.filters.offset > this.meta.total_count)
this.filters.offset = this.meta.total_count;
return this.fetch.call(this, options);
},
fetchPrevious: function(options) {
options = options || {};
options.add = true;
options.at = 0;
this.filters.limit = this.meta.limit;
this.filters.offset = this.meta.offset - this.meta.limit;
if (this.filters.offset < 0){
this.filters.limit += this.filters.offset;
this.filters.offset = 0;
}
return this.fetch.call(this, options);
},
_getQueryString: function() {
if (!this.filters)
return '';
return '?' + $.param(this.filters);
}
});
// Helper function from Backbone to get a value from a Backbone
// object as a property or as a function.
var getValue = function(object, prop) {
if ((object && object[prop]))
return _.isFunction(object[prop]) ? object[prop]() : object[prop];
};
// Helper function from Backbone that raises error when a model's
// url cannot be determined.
var urlError = function() {
throw new Error('A "url" property or function must be specified');
};
})(window.$, window._, window.Backbone);