forked from travis4all/baucis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBackbone.js
More file actions
73 lines (61 loc) · 1.9 KB
/
Backbone.js
File metadata and controls
73 lines (61 loc) · 1.9 KB
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
// Baucis examples using Backbone
// ==============================
(function () {
// A utility function for easily making requests to a Baucis API. Supply Baucis
// options such as `select` or `populate` in the first parameter, and regular
// Backbone fetch options as the second parameter.
function baucisFetch (options, fetchOptions) {
fetchOptions = _.clone(fetchOptions || {});
fetchOptions.data = {};
if (options) {
Object.keys(options).forEach(function (key) {
var value = options[key];
if (typeof value === 'object') fetchOptions.data[key] = JSON.stringify(value);
else fetchOptions.data[key] = value;
});
}
return this.fetch(fetchOptions);
};
// Set up URLs and add baucis fetch method for models/collections
var Vegetables = Backbone.Collection.extend({
url: '/vegetables',
baucis: baucisFetch
});
var Vegetable = Backbone.Model.extend({
urlRoot: '/vegetables',
baucis: baucisFetch
});
// Instantiate a collection and a couple models
var vegetables = new Vegetables();
var tomato = new Vegetable({ _id: 'abcdabcdabcdabcd' });
var potato = new Vegetable({ name: 'Potato' });
// Make some requests and print out the results
// Fetch red vegetables, setting a few options
vegetables.baucis(
{
conditions: { color: 'red' },
populate: 'child',
skip: 20,
limit: 10,
sort: 'foo -bar'
},
{
silent: true
}
).then(function () {
console.log('Fetched Collection:');
console.dir(vegetables.toJSON());
});
// Fetch the model's data based on ID, but select only the `bar` field
tomato.baucis({
select: '-_id bar'
}).then(function () {
console.log('Fetched Entity:');
console.dir(tomato.toJSON());
});
// Save a new vegetable
potato.save().then(function () {
console.log('Saved a potato:');
console.dir(potato.toJSON());
});
})();