-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathbackboneCQRS-0.5.6.js
400 lines (303 loc) · 12.2 KB
/
backboneCQRS-0.5.6.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
// Backbone.CQRS.js
// (c) 2012 Jan Mühlemann
// Backbone.CQRS may be freely distributed under the MIT license.
(function(){
// Initial Setup
// -------------
// Save a reference to the global object.
var root = this;
// Save the value of the `Backbone` variable. All extended modules will
// be appended to Backbone namespace
var Backbone = root.Backbone;
Backbone.CQRS = {};
// Shortcut to underscore
var _ = root._;
// For Backbone's purposes, jQuery or Zepto owns the `$` variable.
var $ = root.jQuery || root.Zepto;
var noop = $.noop;
// Message Objects
// ---------------
Backbone.CQRS.Message = Backbone.Model.extend({
url: noop,
fetch: noop,
save: noop,
destroy: noop
});
// event
var Event = Backbone.CQRS.Message.extend({});
// command
Backbone.CQRS.Command = Backbone.CQRS.Message.extend({
emit: function(callback) {
if (callback) this.observe(callback);
Backbone.CQRS.hub.emit(Backbone.CQRS.hub.commandsChannel, this.parse(this.toJSON()));
},
parse: function(data) {
return data;
},
observe: function(callback) {
Backbone.CQRS.eventHandler.observe(this.id, callback);
}
});
// Event Handling
// --------------
// Hub will listen to events and pass them to the eventdispatcher
var hub = Backbone.CQRS.hub = {
commandsChannel: 'commands',
defaults: {
commandsChannel: 'commands',
eventsChannel: 'events',
eventNameAttr: 'name',
eventModelIdAttr: 'payload.id',
eventResponseToCommandId: 'commandId'
},
init: function(options) {
var self = this;
if (!this.initialized) {
this.initialized = true;
options = _.extend(this.defaults, options);
if (options.parseEvent) this.parseEvent = options.parseEvent;
if (options.getCommandId) this.getCommandId = options.getCommandId;
this.commandsChannel = options.commandsChannel;
// forward incoming events to eventHandler by emitting it to
// dispatchEvent -> eventHandler is bound to this 'channel'
this.on(options.eventsChannel, function(msg) {
// create an event object and set parsed message attributes
var evt = new Event();
evt.set(this.parseEvent(msg));
var attrs = evt.toJSON();
evt.name = dive(attrs, options.eventNameAttr);
evt.id = dive(attrs, options.eventModelIdAttr);
evt.cmdId = self.getCommandId(attrs, options.eventResponseToCommandId);
// emit it -> forward to eventHandler
this.emit('dispatchEvent', evt);
});
}
},
parseEvent: function(msg) {
var evt = msg;
if (typeof evt == 'string') {
evt = JSON.parse(evt);
}
return evt;
},
getCommandId: function(data, field) {
return dive(data, field);
}
};
_.extend(hub, Backbone.Events);
// we use Backbone.Event but provide EventEmitters interface
hub.on = hub.bind;
hub.emit = hub.trigger;
// EventDenormalizer
// --------------
Backbone.CQRS.EventDenormalizer = function(options) {
options = options || {};
if (options.forEvent) this.forEvent = options.forEvent;
if (options.forModel) this.forModel = options.forModel;
if (options.payloadValue) this.payloadValue = options.payloadValue;
if (options.modelIdAttr) this.modelIdAttr = options.modelIdAttr;
if (options.onHandle) this.onHandle = options.onHandle;
this.methode = options.methode || 'update';
this.model = options.model;
this.collection = options.collection;
if (this.forEvent && this.forModel) this.register.apply(this);
this.initialize.apply(this, arguments);
};
// Set up all inheritable properties and methods.
_.extend(Backbone.CQRS.EventDenormalizer.prototype, Backbone.Events, {
defaultPayloadValue: 'payload',
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize : noop,
// will be called by Backbone.CQRS.eventHandler
// models can listen to this event via myModel.bindCQRS()
handle: function (evt) {
var id = this.modelIdAttr ? dive(evt.toJSON(), this.modelIdAttr) : evt.id;
if (this.methode !== 'create') {
if (id) {
this.trigger('change:' + id, this.parse(evt), this.apply(this.methode));
}
} else {
var col = (typeof this.collection == 'function') ? this.collection(evt) : this.collection;
if (!col) return;
var data = this.parse(evt);
col.add(data);
if (this.onHandle) this.onHandle(data, col.get(id));
}
},
// as the denormalizer is for a specific model it can provide an
// apply function for the model
apply: function(methode) {
var self = this;
return function(data, model) {
if (methode === 'delete') {
// unbind it
if (model.isCQRSBound) model.unbindCQRS();
// destroy it
model.destroy();
if (self.onHandle) self.onHandle(data, model);
} else {
model.set(data);
if (self.onHandle) self.onHandle(data, model);
}
};
},
// get the needed part from event to apply to model
parse: function(evt) {
if (this.payloadValue || this.defaultPayloadValue) {
diveTo = this.payloadValue || this.defaultPayloadValue;
return dive(evt.toJSON(), diveTo);
} else {
return evt.toJSON();
}
},
// used to add denormalizer to Backbone.CQRS.eventHandler which forwards
// event to specific denormalizers handle function
register: function(forEvt, forMdl) {
this.forEvent = forEvt || this.forEvent;
this.forModel = forMdl || this.forModel;
Backbone.CQRS.eventHandler.register(this);
}
});
Backbone.CQRS.EventDenormalizer.extend = Backbone.Model.extend;
// Global EventHandler
// -------------------
var EventHandler = Backbone.CQRS.EventDenormalizer.extend({
initialize: function() {
this.denormalizers = [];
this.observedCommands = [];
// subscribe on incoming events
Backbone.CQRS.hub.on('dispatchEvent', function(evt) {
this.handle(evt);
}, this);
},
// get specific denormalizer for model or event type
getDenormalizer: function(forEvent, forModel) {
if (forEvent) {
return _(this.denormalizers).filter(function(r) {
return r.forEvent == forEvent;
});
} else if (forModel) {
return _(this.denormalizers).filter(function(r) {
return r.forModel == forModel;
});
} else {
return null;
}
},
// handles incoming events from hub
handle: function(evt) {
// to denormalizers
var denorm = this.getDenormalizer(evt.name);
_(denorm).each(function(d) {
d.handle(evt);
});
// to observing commands
var pending = this.getPendingCommand(evt);
if (pending) {
pending.callback(evt);
this.removePendingCommand(pending);
}
},
// a model can bind to events via ev = 'modelName:id'
// this will happen on myModel.bindCQRS()
// the binding is forwarded to matching denormalizers
bind: function(ev, callback, context) {
if (ev.indexOf(':') < 0) return false;
var modelName = ev.substring(0, ev.indexOf(':')),
evtName = 'change:' + ev.substring(ev.indexOf(':') + 1, ev.length);
var denorm = this.getDenormalizer(null, modelName);
_(denorm).each(function(d) {
d.bind(evtName, callback, context);
});
},
unbind: function(ev, callback) {
if (ev.indexOf(':') < 0) return false;
var parts = ev.split(':'),
modelName = parts[0],
evtName = 'change:' + parts[1];
var denorm = this.getDenormalizer(null, modelName);
_(denorm).each(function(d) {
d.unbind(evtName, callback);
});
},
// add command to observe
// in the handle function an event matching the command will
// call the provided callback
observe: function(cmdId, callback) {
this.observedCommands.push({id: cmdId, callback: callback});
},
getPendingCommand: function(evt) {
return _.detect(this.observedCommands, function(pend) {
return pend.id == evt.cmdId;
});
},
removePendingCommand: function(pending) {
var index = _.indexOf(this.observedCommands, pending);
this.observedCommands.splice(index, 1);
},
register: function(denormalizer) {
this.denormalizers.push(denormalizer);
}
});
// create one instace of this global handler
Backbone.CQRS.eventHandler = new EventHandler();
// Extend Backbone.Model
// ---------------------
Backbone.Model = Backbone.Model.extend({
modelName: null, // you should set this in your model or provide val on bindCQRS
// just an easier shortcut to Backbone.CQRS.eventHandler.bind
bindCQRS: function(modelName) {
if (modelName) this.modelName = modelName;
if (!this.modelName) return;
var id = this.id || this.cid;
Backbone.CQRS.eventHandler.bind(this.modelName + ':' + id, this.apply, this);
this.isCQRSBound = true;
},
unbindCQRS: function(modelName) {
if (modelName) this.modelName = modelName;
if (!this.modelName) return;
var id = this.id || this.cid;
Backbone.CQRS.eventHandler.unbind(this.modelName + ':' + id, this.apply, this);
this.isCQRSBound = false;
},
// will call the provided function with the data from denormalizer
// so you can have denormalizing functionality capsulated in denormalizer
// override this with you function if needed just be aware all matching
// events (eg. personCreated, personChange) will call the same function
apply: function(data, funct) {
funct.apply(this, [data, this]);
}
});
// Modified Backbone.Sync
// ----------------------
var origSync = Backbone.sync;
Backbone.CQRS.sync = function(method, model, options) {
var type = methodMap[method];
// __only change is here__ only allow get!
if (type !== 'GET') {
return options.success(model, null, options);
} else {
origSync(method, model, options);
}
};
// Functions
// ---------
var dive = function(obj, key) {
var keys = key.split('.');
var x = 0;
var value = obj;
while (keys[x]) {
value = value && value[keys[x]];
x++;
}
return value;
};
// Mappings from backbone to server methode.
var methodMap = {
'create': 'POST',
'update': 'PUT',
'delete': 'DELETE',
'read': 'GET'
};
}).call(this);