forked from GeppettoJS/backbone.geppetto
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbackbone.geppetto.js
executable file
·466 lines (379 loc) · 14.3 KB
/
backbone.geppetto.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
// backbone.geppetto 0.7.1
//
// Copyright (C) 2013 Dave Cadwallader, Model N, Inc.
// Distributed under the MIT License
//
// Documentation and full license available at:
// http://modeln.github.com/backbone.geppetto/
(function(factory) {
// CommonJS
if (typeof exports === "object") {
module.exports = factory(require('underscore'), require('backbone'));
} else if (typeof define === "function" && define.amd) {
// Register as an AMD module if available...
define(["underscore", "backbone"], factory);
} else {
// Browser globals for the unenlightened...
factory(_, Backbone);
}
}(function(_, Backbone) {
"use strict";
if (!Backbone) {
throw "Please include Backbone before Geppetto";
}
var NO_MAPPING_FOUND = 'no mapping found for key: ';
var TYPES = {
SINGLETON: 'singleton',
VIEW: 'view',
OTHER: 'other'
};
//based on http://stackoverflow.com/questions/3362471/how-can-i-call-a-javascript-constructor-using-call-or-apply
function applyToConstructor(constructor, argArray) {
var args = [constructor, null].concat(argArray);
var FactoryFunction = _.bind.apply(constructor, args);
return new FactoryFunction();
}
function createFactory(clazz) {
return function() {
return applyToConstructor(clazz, _.toArray(arguments));
};
}
var extractConfig = function(def, key) {
var thisCtor, thisWiring;
if (def.hasOwnProperty("ctor")) {
thisCtor = def.ctor;
thisWiring = def.wiring;
} else {
thisCtor = def;
}
return [key, thisCtor, thisWiring];
};
var validateListen = function(target, eventName, callback) {
if (!_.isObject(target) || !_.isFunction(target.listenTo) || !_.isFunction(target.stopListening)) {
throw "Target for listen() must define a 'listenTo' and 'stopListening' function";
}
if (!_.isString(eventName)) {
throw "eventName must be a String";
}
if (!_.isFunction(callback)) {
throw "callback must be a function";
}
};
var Geppetto = {};
Geppetto.version = '0.7.1';
Geppetto.EVENT_CONTEXT_SHUTDOWN = "Geppetto:contextShutdown";
var contexts = {};
Geppetto.Context = function Context(options) {
this._mappings = {};
this.options = options || {};
this.parentContext = this.options.parentContext;
this.vent = {};
_.extend(this.vent, Backbone.Events);
this._contextId = _.uniqueId("Context");
contexts[this._contextId] = this;
var wiring = this.wiring || this.options.wiring;
if (wiring) {
this._configureWirings(wiring);
}
if (_.isFunction(this.initialize)) {
this.initialize.apply(this, arguments);
}
};
Geppetto.Context.extend = Backbone.View.extend;
_.extend(Geppetto.Context.prototype, {
_configureWirings: function _configureWirings(wiring) {
var _this = this;
_.each(wiring.singletons, function(def, key) {
_this.wireSingleton.apply(_this, extractConfig(def, key));
});
_.each(wiring.classes, function(def, key) {
_this.wireClass.apply(_this, extractConfig(def, key));
});
_.each(wiring.values, function(value, key) {
_this.wireValue(key, value);
});
_.each(wiring.views, function(def, key) {
_this.wireView.apply(_this, extractConfig(def, key));
});
this.wireCommands(wiring.commands);
},
_createAndSetupInstance: function(config) {
var instance,
_this = this;
if (config.params) {
var params = _.map(config.params, function(param) {
if (_.isFunction(param)) {
param = param(_this);
}
return param;
});
instance = applyToConstructor(config.clazz, params);
} else {
instance = new config.clazz();
}
if (!instance.initialize) {
this.resolve(instance, config.wiring);
}
return instance;
},
_retrieveFromCacheOrCreate: function(key, overrideRules) {
var output;
if (this._mappings.hasOwnProperty(key)) {
var config = this._mappings[key];
if (!overrideRules && config.type === TYPES.SINGLETON) {
if (!config.object) {
config.object = this._createAndSetupInstance(config);
}
output = config.object;
} else {
if (config.type === TYPES.VIEW) {
output = config.clazz;
} else if (config.clazz) {
output = this._createAndSetupInstance(config);
}
}
} else if (this.parentContext && this.parentContext.hasWiring(key)) {
output = this.parentContext._retrieveFromCacheOrCreate(key, overrideRules);
} else {
throw new Error(NO_MAPPING_FOUND + key);
}
return output;
},
_wrapConstructor: function(clazz, wiring) {
var context = this;
if (clazz.extend) {
return clazz.extend({
constructor: function() {
context.resolve(this, wiring);
clazz.prototype.constructor.apply(this, arguments);
}
});
} else {
return clazz;
}
},
_mapContextEvents: function(obj) {
var _this = this;
_.each(obj.contextEvents, function(callback, eventName) {
if (_.isFunction(callback)) {
_this.listen(obj, eventName, callback);
} else if (_.isString(callback)) {
_this.listen(obj, eventName, obj[callback]);
}
});
},
addPubSub: function(instance) {
instance.listen = _.bind(this.listen, this);
instance.dispatch = _.bind(this.dispatch, this);
},
listen: function listen(target, eventName, callback) {
validateListen(target, eventName, callback);
return target.listenTo(this.vent, eventName, callback, target);
},
listenToOnce: function listenToOnce(target, eventName, callback) {
validateListen(target, eventName, callback);
return target.listenToOnce(this.vent, eventName, callback, target);
},
dispatch: function dispatch(eventName, eventData) {
if (!_.isUndefined(eventData) && !_.isObject(eventData)) {
throw "Event payload must be an object";
}
eventData = eventData || {};
eventData.eventName = eventName;
this.vent.trigger(eventName, eventData);
},
dispatchToParent: function dispatchToParent(eventName, eventData) {
if (this.parentContext) {
this.parentContext.vent.trigger(eventName, eventData);
}
},
dispatchToParents: function dispatchToParents(eventName, eventData) {
if (this.parentContext && !(eventData && eventData.propagationDisabled)) {
this.parentContext.vent.trigger(eventName, eventData);
if (this.parentContext) {
this.parentContext.dispatchToParents(eventName, eventData);
}
}
},
dispatchGlobally: function dispatchGlobally(eventName, eventData) {
_.each(contexts, function(context) {
if (!context) {
return true;
}
context.vent.trigger(eventName, eventData);
});
},
wireCommand: function wireCommand(eventName, CommandConstructor, wiring) {
var context = this;
if (!_.isFunction(CommandConstructor)) {
throw "Command must be constructable";
}
this.vent.listenTo(this.vent, eventName, function(eventData) {
var commandInstance = new CommandConstructor(context, eventName, eventData);
commandInstance.context = context;
commandInstance.eventName = eventName;
commandInstance.eventData = eventData;
context.resolve(commandInstance, wiring);
if (_.isFunction(commandInstance.execute)) {
commandInstance.execute();
}
});
},
wireCommands: function wireCommands(commandsMap) {
var _this = this;
_.each(commandsMap, function(mixedType, eventName) {
if (_.isArray(mixedType)) {
_.each(mixedType, function(commandClass) {
_this.wireCommand(eventName, commandClass);
});
} else {
_this.wireCommand(eventName, mixedType);
}
});
},
wireValue: function(key, useValue) {
this._mappings[key] = {
clazz: null,
object: useValue,
type: TYPES.SINGLETON
};
return this;
},
wireClass: function(key, clazz, wiring) {
this._mappings[key] = {
clazz: this._wrapConstructor(clazz, wiring),
object: null,
type: TYPES.OTHER,
wiring: wiring
};
return this;
},
wireView: function(key, clazz, wiring) {
this._mappings[key] = {
clazz: createFactory(this._wrapConstructor(clazz, wiring)),
object: null,
type: TYPES.VIEW
};
return this;
},
wireSingleton: function(key, clazz, wiring) {
this._mappings[key] = {
clazz: this._wrapConstructor(clazz, wiring),
object: null,
type: TYPES.SINGLETON,
wiring: wiring
};
return this;
},
configure: function(key) {
var mapping = this._mappings[key];
if (typeof mapping === 'undefined') {
throw new Error(NO_MAPPING_FOUND + key);
}
if (!mapping.clazz || mapping.type === TYPES.VIEW) {
throw new Error("Cannot configure " + key + ": only possible for wirings of type singleton or class");
}
mapping.params = _.toArray(arguments).slice(1);
},
hasWiring: function(key) {
return this._mappings.hasOwnProperty(key) || (!!this.parentContext && this.parentContext.hasWiring(key));
},
getObject: function(key) {
return this._retrieveFromCacheOrCreate(key, false);
},
instantiate: function(key) {
return this._retrieveFromCacheOrCreate(key, true);
},
resolve: function(instance, wiring) {
var _this = this;
wiring = wiring || instance.wiring;
if (wiring) {
var propNameArgIndex = Number(!_.isArray(wiring));
_.each(wiring, function(dependencyKey) {
instance[arguments[propNameArgIndex]] = _this.getObject(dependencyKey);
});
}
this.addPubSub(instance);
this._mapContextEvents(instance);
return this;
},
release: function(key) {
delete this._mappings[key];
return this;
},
releaseAll: function() {
this._mappings = {};
return this;
},
destroy: function destroy() {
this.vent.stopListening();
this.releaseAll();
delete contexts[this._contextId];
this.dispatchToParent(Geppetto.EVENT_CONTEXT_SHUTDOWN);
}
});
Geppetto.bindContext = function bindContext(options) {
this.options = options || {};
var view = this.options.view;
var context = null;
if (typeof this.options.context === 'function') {
// create new context if we get constructor
context = new this.options.context(this.options);
// only close context if we are the owner
if (!view.close) {
view.close = function() {
view.trigger("close");
view.remove();
};
}
view.on("close", function() {
view.off("close");
context.destroy();
});
} else if (typeof this.options.context === 'object') {
// or use existing context if we get one
context = this.options.context;
}
context.resolve(view);
var returnValue;
// only set a reference to the context on the view if the view
// is a pre-0.7.0 component that does not use dependency injection.
// this will be removed in a future release...
if (!view.wiring) {
view.context = context;
returnValue = context;
}
return returnValue;
};
var debug = {
contexts: contexts,
countEvents: function countEvents() {
var numEvents = 0;
_.each(contexts, function(context, id) {
if (contexts.hasOwnProperty(id)) {
numEvents += _.size(context.vent._events);
}
});
return numEvents;
},
countContexts: function countContexts() {
var numContexts = 0;
_.each(contexts, function(context, id) {
if (contexts.hasOwnProperty(id)) {
numContexts++;
}
});
return numContexts;
}
};
Geppetto.setDebug = function setDebug(enableDebug) {
if (enableDebug) {
this.debug = debug;
} else {
this.debug = undefined;
}
return this.debug;
};
Backbone.Geppetto = Geppetto;
return Geppetto;
}));