forked from zuk/Backbone.Drowsy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wakeful.js
286 lines (269 loc) · 9.25 KB
/
wakeful.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// Generated by CoffeeScript 1.7.1
(function() {
var $, Backbone, Drowsy, Faye, Wakeful, readVal, root, _;
if (typeof window !== "undefined" && window !== null) {
$ = window.$;
_ = window._;
Backbone = window.Backbone;
Drowsy = window.Drowsy;
Faye = window.Faye;
} else {
$ = require('jquery');
_ = require('underscore');
Backbone = require('backbone');
Backbone.$ = $;
Drowsy = require('./backbone.drowsy').Drowsy;
Faye = require('faye');
global.window = {};
}
readVal = function(context, val) {
if (_.isFunction(val)) {
return val.call(context);
} else {
return val;
}
};
Wakeful = (function() {
function Wakeful() {}
_.extend(Wakeful, Backbone.Events);
if (Faye != null) {
Wakeful.Faye = Faye;
}
if (Wakeful.fayeClients == null) {
Wakeful.fayeClients = {};
}
Wakeful.subs = [];
Wakeful.sync = function(method, obj, options) {
var changed, changedJSON, data, deferredSync, temp;
deferredSync = $.Deferred();
data = obj.toJSON();
if (method === 'read') {
Backbone.sync(method, obj, options).fail(function(xhr) {
var err;
console.error("ERROR", xhr.responseText);
obj.trigger('sync:error', obj, xhr, options);
err = new Error(xhr.status + ": " + xhr.responseText);
return deferredSync.reject(err);
}).done(function() {
obj.dirty = {};
return deferredSync.resolve();
});
} else {
switch (method) {
case 'create':
case 'update':
obj.broadcast(method, data);
break;
case 'patch':
changed = obj.dirtyAttributes();
temp = new Drowsy.Document(changed);
changedJSON = temp.toJSON();
delete changedJSON._id;
obj.broadcast(method, changedJSON);
break;
case 'delete':
obj.broadcast(method, obj);
}
obj.dirty = {};
obj.trigger('sync', obj, changed != null ? changed : data, options);
deferredSync.resolve();
}
return deferredSync;
};
Wakeful.wake = function(obj, fayeUrl, options) {
if (options == null) {
options = {};
}
if ((obj.fayeUrl != null) && obj.fayeUrl === fayeUrl) {
console.log(obj, "is already awake... skipping");
return;
}
if (fayeUrl == null) {
throw new Error("Must provide a fayeUrl");
}
obj.fayeUrl = fayeUrl;
obj.broadcastEchoQueue = [];
Wakeful.fayeClients[fayeUrl] = new Wakeful.Faye.Client(fayeUrl, {
timeout: 35
});
obj.faye = Wakeful.fayeClients[fayeUrl];
obj.sync = Wakeful.sync;
obj = _.extend(obj, {
subscriptionUrl: function() {
var coll, db, drowsyUrl, id, parsedUrl, rx, url;
drowsyUrl = readVal(this, this.url);
rx = /[a-z]+:\/\/[^\/]+\/([^\/\.]+)\/(\w[^\/\$]*)(?:\/([0-9a-f]{24}))?/;
parsedUrl = drowsyUrl.match(rx);
if (parsedUrl == null) {
console.error(drowsyUrl, "is not a valid Drowsy URL usable with WakefulWeasel");
throw new Error('Invalid Drowsy URL', drowsyUrl);
}
url = parsedUrl[0], db = parsedUrl[1], coll = parsedUrl[2], id = parsedUrl[3];
if (id != null) {
return "/" + db + "/" + coll + "/" + id;
} else {
return "/" + db + "/" + coll + "/*";
}
},
tunein: function() {
var deferredSub;
if (this instanceof Drowsy.Document && !this.has('_id')) {
console.error("Wakeful cannot tunein for this object because it does not yet been assigned an id!", this);
throw new Error("Cannot call tunein() on Drowsy.Document because it has not yet been assigned an id", this);
}
deferredSub = $.Deferred();
this.sub = this.faye.subscribe(this.subscriptionUrl(), _.bind(this.receiveBroadcast, this));
this.sub.callback(function() {
return deferredSub.resolve();
});
this.sub.errback(function(err) {
return deferredSub.reject(err);
});
Wakeful.subs.push(this.sub);
return deferredSub;
},
tuneout: function() {
sub.cancel();
return delete this.sub;
},
broadcast: function(action, data) {
var bcast, bid, deferredPub, pub, toChannel;
deferredPub = $.Deferred();
bid = Drowsy.generateMongoObjectId();
if ((data._id == null) && (this.id != null)) {
data._id = this.id;
}
if (data._id == null) {
console.warn("Cannot broadcast data for a Drowsy.Document without an id!", data, this);
deferredPub.reject('missing_id');
return deferredPub;
}
bcast = {
action: action,
data: data,
bid: bid
};
this.broadcastEchoQueue.push(deferredPub);
toChannel = this.subscriptionUrl();
if (this instanceof Drowsy.Collection) {
toChannel = toChannel.replace(/\*$/, '~');
}
pub = this.faye.publish(toChannel, bcast);
this.trigger('wakeful:broadcast:sent', bcast);
deferredPub.notify('sent');
pub.callback((function(_this) {
return function() {
_this.trigger('wakeful:broadcast:confirmed', bcast);
return deferredPub.notify('confirmed');
};
})(this));
pub.errback((function(_this) {
return function(err) {
console.warn("Broadcast #" + bid + " failed!", err, bcast);
_this.trigger('wakeful:broadcast:error', bcast, err);
return deferredPub.reject(err);
};
})(this));
deferredPub.pub = pub;
deferredPub.bid = bid;
return deferredPub;
},
receiveBroadcast: function(bcast) {
var docs, echoIndex, echoOf;
echoOf = _.find(this.broadcastEchoQueue, function(defPub) {
return defPub.bid === bcast.bid;
});
if (echoOf != null) {
echoIndex = _.indexOf(this.broadcastEchoQueue, echoOf);
this.broadcastEchoQueue.splice(echoIndex, 1);
this.trigger('wakeful:broadcast:echo', bcast);
echoOf.resolve();
return;
}
this.trigger('wakeful:broadcast:received', bcast);
switch (bcast.action) {
case 'update':
case 'patch':
case 'create':
if (this instanceof Drowsy.Document) {
return this.set(this.parse(bcast.data));
} else {
if (_.isArray(bcast.data)) {
docs = bcast.data;
if (bcast.action === 'patch' && (bcast.data == null)) {
console.error("PATCH received by collection will be ignored because the broadcast data did not include a document id (_id)", bcast);
return;
}
} else {
docs = [bcast.data];
}
docs = docs.map((function(_this) {
return function(doc) {
return _this.model.prototype.parse(doc);
};
})(this));
return this.set(docs, {
remove: false
});
}
break;
case 'delete':
if (this instanceof Drowsy.Document) {
return this.destroy({
wait: true
});
} else {
if (this.get(bcast.data._id)) {
return this.get(bcast.data._id).destroy({
wait: true
});
}
}
break;
default:
return console.warn("Don't know how to handle broadcast with action", bcast.action);
}
}
});
obj.faye.bind('transport:up', (function(_this) {
return function() {
_this.trigger('transport:up');
return Wakeful.trigger('transport:up', obj);
};
})(this));
obj.faye.bind('transport:down', (function(_this) {
return function() {
_this.trigger('transport:down');
return Wakeful.trigger('transport:down', obj);
};
})(this));
if (options.tunein !== false) {
return obj.tunein();
}
};
Wakeful.loadFayeClient = function(fayeUrl) {
var deferredLoad;
deferredLoad = $.Deferred();
$.getScript("" + fayeUrl + "/client.js", function(script) {
Wakeful.Faye = window.Faye;
return deferredLoad.resolve();
});
return deferredLoad;
};
return Wakeful;
})();
Drowsy.Document.prototype.wake = function(fayeUrl, options) {
if (options == null) {
options = {};
}
return Wakeful.wake(this, fayeUrl, options);
};
Drowsy.Collection.prototype.wake = function(fayeUrl, options) {
if (options == null) {
options = {};
}
return Wakeful.wake(this, fayeUrl, options);
};
root = typeof exports !== "undefined" && exports !== null ? exports : this;
root.Wakeful = Wakeful;
}).call(this);