-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathbackpusher.js
108 lines (86 loc) · 2.84 KB
/
backpusher.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
105
106
107
108
// Backpusher.js 0.0.2
// (c) 2011-2012 Pusher.
// Backpusher may be freely distributed under the MIT license.
// For all details and documentation:
// http://github.com/pusher/backpusher
;(function(exports, undefined){
// The top-level namespace. All public Backbone classes and modules will
// be attached to this. Exported for both CommonJS and the browser.
var Backpusher = function(channel, collection, options) {
if (!(this instanceof Backpusher)) {
return new Backpusher(channel, collection, options);
}
// Bind for the connection established, so
// we can setup the socket_id param.
if (channel.pusher.connection) {
channel.pusher.connection.bind('connected', function() {
Backbone.pusher_socket_id = channel.pusher.connection.socket_id;
});
} else {
channel.pusher.bind('pusher:connection_established', function() {
Backbone.pusher_socket_id = channel.pusher.socket_id;
});
}
// Options is currently unused:
this.options = (options || {});
this.channel = channel;
this.collection = collection;
if (this.options.events) {
this.events = this.options.events;
} else {
this.events = Backpusher.defaultEvents;
}
this._bindEvents();
this.initialize(channel, collection, options);
};
_.extend(Backpusher.prototype, Backbone.Events, {
initialize: function() {},
_bindEvents: function() {
if (!this.events) return;
for (var event in this.events) {
this.channel.bind(event, _.bind(this.events[event], this));
}
},
_add: function(model) {
var Collection = this.collection;
model = new Collection.model(model);
Collection.add(model);
this.trigger('remote_create', model);
return model;
}
});
Backpusher.defaultEvents = {
created: function(pushed_model) {
return this._add(pushed_model);
},
updated: function(pushed_model) {
var model = this.collection.get(pushed_model);
if (model) {
model = model.set(pushed_model);
this.trigger('remote_update', model);
return model;
} else {
return this._add(pushed_model);
}
},
destroyed: function(pushed_model) {
var model = this.collection.get(pushed_model);
if (model) {
this.collection.remove(model);
this.trigger('remote_destroy', model);
return model;
}
}
};
// Add socket ID to every Backbone.sync request
var origBackboneSync = Backbone.sync;
Backbone.sync = function(method, model, options) {
options.headers = _.extend(
{ 'X-Pusher-Socket-ID': Backbone.pusher_socket_id },
options.headers
);
return origBackboneSync(method, model, options);
};
// Export:
exports.Backpusher = Backpusher;
})((typeof exports !== 'undefined' ? exports : this));