This repository has been archived by the owner on Oct 30, 2018. It is now read-only.
/
mojito-client.client.js
1072 lines (925 loc) · 39.7 KB
/
mojito-client.client.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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2011-2012, Yahoo! Inc. All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
/*jslint anon:true, sloppy:true, nomen:true*/
/*global YUI*/
// Set up a global client-side Mojito namespace
if (!YUI._mojito) {
/**
* The top-level Mojito namespace.
* @type {Object}
*/
YUI._mojito = {
// this is initially a dummy logger object so that client code can set
// mutator functions before the logger has actually been instantiated
logger: {
_logMutatorCache: {
publisher: function() {
YUI._mojito._clientYlog.apply(YUI._mojito._clientY,
arguments);
}
},
set: function(k, v) {
this._logMutatorCache[k] = v;
}
},
// A general cache object to be used by internal mojito only
_cache: {},
_clientY: null,
_clientYlog: null
};
}
YUI.add('mojito-client', function(Y, NAME) {
// These methods are methods that potentially make XHR calls to retrieve
// data from the server. When the Mojito client is "paused" by calling the
// pause() function, all the methods below are queued as they are executed
// instead of being fully executed. When the resume() function is called,
// the pause queue is flushed and all the intercepted actions are taken at
// that time.
var PAUSEABLE = [
'executeAction',
'doRender',
'doBroadcast',
'doListen',
'doUnlisten'
],
log,
lifecycleEvents,
State = {
PAUSED: 'paused',
ACTIVE: 'active'
};
// because there is a moment during startup when we need it, cache the
// original Y instance for use as the log platform
// And don't clobber the global
if (!YUI._mojito._clientY) {
YUI._mojito._clientY = Y;
}
log = function() {
if (YUI._mojito.logger && YUI._mojito.logger.log) {
YUI._mojito.logger.log.apply(YUI._mojito.logger, arguments);
} else {
YUI._mojito._clientY.log.apply(YUI._mojito._clientY, arguments);
}
};
// this is the heart of mojitProxy.render(), but it needs to be a separate
// function called once we have mojit type details
function privateRender(mp, data, view, cb) {
var mojitView,
renderer;
if (!mp._views || !mp._views[view]) {
cb(new Error('View "' + view + '" not found'));
return;
}
data = data || {};
// this is presumed to be useful enough that we'll set it up for them
data.mojit_assets = data.mojit_assets || mp._assetsRoot;
mojitView = mp._views[view];
renderer = new Y.mojito.ViewRenderer(mojitView.engine);
Y.log('Rendering "' + view + '" in Binder', 'debug', NAME);
renderer.render(data, mp.type, mojitView['content-path'], {
buffer: '',
flush: function(data) {
this.buffer += data;
},
done: function(data) {
this.buffer += data;
cb(null, this.buffer);
}
});
}
function setNewMojitView(viewData, mp) {
Y.log('setting new view on mojit ' + mp._instanceId, 'debug', NAME);
var newNode = Y.Node.create(viewData);
mp._node.replace(newNode);
mp._element = document.getElementById(mp._viewId);
mp._node = new Y.Node(mp._element);
if (Y.Lang.isFunction(mp._binder.onRefreshView)) {
mp._binder.onRefreshView(mp._node, mp._element);
}
}
// we have to match the children by instanceId to identify them and replace
// their viewId with the actual viewId for the binder that should be
// attached.
function processChildren(children, binderMap) {
var name,
viewId,
found;
for (name in children) {
if (children.hasOwnProperty(name)) {
for (viewId in binderMap) {
if (binderMap.hasOwnProperty(viewId) && !found) {
if (binderMap[viewId].instanceId ===
children[name].instanceId) {
children[name].viewId = viewId;
found = true;
}
}
}
found = false;
}
}
return children;
}
function bindNode(binder, node, element) {
var handles = [];
if (Y.Lang.isFunction(binder.bind)) {
// Pass the "node" to the bind method
binder.bind(node, element);
}
// all automatic event delegation
if (Y.Lang.isFunction(binder.handleClick)) {
// This code should be deferred till after the page has visibly
// loaded
handles.push(Y.delegate('click', binder.handleClick, node,
function() { return true; },
binder));
}
// TODO: add all the event delegation majic here.
Y.log('Attached ' + handles.length + ' event delegates', 'debug', NAME);
return handles;
}
// TODO: complete work to call this in the destroyMojitProxy function().
function unbindNode(binder, handles) {
var retainBinder = false;
if (Y.Lang.isFunction(binder.unbind)) {
// let the binder decide whether it wants to stick around in case
// its node is reattached at some point in the future
retainBinder = binder.unbind.call(binder);
}
if (handles) {
Y.Array.each(handles, function(handle) {
Y.log('Detaching event handle from binder', 'debug', NAME);
handle.detach();
});
}
return retainBinder;
}
function findParentProxy(mojits, childId) {
var p;
// TODO: convert to "some" instead of each for performance. We're doing
// a "detect" here.
Y.Object.each(mojits, function(mojit) {
Y.Object.each(mojit.children, function(child) {
if (child.viewId === childId) {
p = mojit.proxy;
return true;
}
});
if (p) {
return true;
}
});
return p;
}
/**
* The starting point for mojito to run in the browser. You can access one
* instance of the Mojito Client running within the browser environment
* through window.YMojito.client.
* @module MojitoClient
* @class Client
* @constructor
* @namespace Y.mojito
* @param {Object} config The entire configuration object written by the
* server to start up mojito.
*/
function MojitoClient(config) {
this.timeLogStack = [];
this.yuiConsole = null;
this._pauseQueue = [];
if (config) {
this.init(config);
}
}
lifecycleEvents = {};
/**
* Subscribe to a MojitoClient lifecycle event.
* @method subscribe
* @param {string} evt name of event to subscribe to.
* @param {function(data)} cb callback called when the event fires.
*/
MojitoClient.subscribe = function(evt, cb) {
// Subscribe works only in appLevel
if (Y && YUI._mojito._clientY &&
(Y._yuid !== YUI._mojito._clientY._yuid)) {
// Y.log('Applevel subscribe ? ' + Y._yuid + " ==== " +
// YUI._mojito._clientY._yuid, 'error', NAME);
return;
}
if (!lifecycleEvents[evt]) {
lifecycleEvents[evt] = [];
}
lifecycleEvents[evt].push(cb);
};
/**
* Fires a lifecycle event.
* @method fireLifecycle
* @param {string} evt The name of event to fire.
* @param {Object} data The data to pass to listeners.
* @private
*/
function fireLifecycle(evt, data) {
var cbs = lifecycleEvents[evt],
c;
if (!cbs || !cbs.length) {
return;
}
for (c = 0; c < cbs.length; c += 1) {
cbs[c](data);
}
}
/**
* Fired at the beginning of the startup of MojitoClient.
*
* The data contains the following:
* <dl>
* <dt><code>config</code></dt>
* <dd>the config object used to initialize the MojitoClient</dd>
* </dl>
*
* Any change to the config will be picked up and used by MojitoClient.
* @param {Object} data The data for the event.
*/
/**
* Fired at the end of the startup of MojitoClient.
* @param {Object} data The data for the event. (Empty in this case).
*/
/**
* Fired before the binders are attached to the page.
*
* The data contains the following:
* <dl>
* <dt><code>binderMap</code></dt>
* <dd>the details of the binders to attach to the page</dd>
* <dt><code>parentId</code></dt>
* <dd>[optional] the parent binder view id to attach any children</dd>
* <dt><code>topLevelMojitViewId</code></dt>
* <dd>[optional] the topmost (root) binder view id to attach as a child to
* the parent</dd>
* </dl>
*
* Any change to the data will be picked up and used by MojitoClient.
* @param {Object} data The data for the event.
*/
/**
* Fired after the binders are attached to the page.
* @param {Object} data The data for the event. (Empty in this case).
*/
MojitoClient.prototype = {
init: function(config) {
fireLifecycle('pre-init', {config: config});
Y.mojito.perf.mark('mojito', 'core_client_start');
var that = this,
logConfig = {},
appConfig = config.appConfig;
// YUI Console
if (appConfig && appConfig.yui &&
appConfig.yui.showConsoleInClient && !that.yuiConsole) {
YUI().use('console-filters', function(Y) {
Y.one('body').addClass('yui3-skin-sam');
that.yuiConsole = new Y.Console({
plugins: [Y.Plugin.ConsoleFilters],
logSource: Y.Global,
height: 600
});
that.yuiConsole.render();
that.init(config);
});
return;
}
if (appConfig && appConfig.log && appConfig.log.client) {
logConfig = appConfig.log.client;
}
// to allow any client code to provide global log mutators before
// mojito starts...
Y.Array.each(['formatter', 'writer', 'publisher'],
function(logMutator) {
if (YUI._mojito.logger._logMutatorCache[logMutator]) {
logConfig[logMutator] =
YUI._mojito.logger._logMutatorCache[logMutator];
}
});
// Don't clobber globals
if (!YUI._mojito.logger.log) {
YUI._mojito.logger = new Y.mojito.Logger(logConfig);
}
if (!YUI._mojito.loader) {
YUI._mojito.loader = new Y.mojito.Loader(appConfig,
config.pathToRoot);
}
// push all client logs through our logger
if (!YUI._mojito._clientYlog) {
YUI._mojito._clientYlog = Y.log;
}
Y.log = log;
if (Y.mojito.TunnelClient) {
this.tunnel = new Y.mojito.TunnelClient(config.appConfig);
}
// Make the "Resource Store" by wrapping it with the adapter
this.resourceStore = new Y.mojito.ResourceStore(config);
// the resource store adapter and the dispatcher must be passed the
// mojito logger object, because they were created within a Y scope
// that still has reference to the original Y.log function
this.resourceStore = Y.mojito.ResourceStoreAdapter.init('client',
this.resourceStore, YUI._mojito.logger);
this.dispatcher = Y.mojito.Dispatcher.init(this.resourceStore,
null, YUI._mojito.logger, YUI._mojito.loader);
// request context from server
this.context = config.context;
// application configuration
this.config = config;
// create listener bag for mojit comms
this._listeners = {};
// the mojits represented in the current DOM, keyed by DOM element
// id
this._mojits = {};
Y.mojito.perf.mark('mojito',
'core_client_end', 'Mojito client library loaded');
/* FUTURE -- perhaps only do this once a user needs it
var singletons;
singletons = {
tunnel: this.tunnel,
resourceStore: this.resourceStore,
dispatcher: this.dispatcher
}
fireLifecycle('made-singletons', singletons);
// allow the event listeners to modify the singletons
this.tunnel = singletons.tunnel;
this.resourceStore = singletons.resourceStore;
this.dispatcher = singletons.dispatcher;
*/
this.attachBinders(config.binderMap);
// wrap pause-able methods
Y.Array.each(PAUSEABLE, function(mName) {
var me = this,
originalMethod = me[mName];
this[mName] = function() {
// during execution of these pauseable function, we'll check
// to see if the client is in a paused state
if (me._state === State.PAUSED) {
// now just queue the method call with original function
// and args for execution on resume()
me._pauseQueue.push({
fn: originalMethod,
args: arguments
});
} else {
// not paused, so go ahead and apply the function
originalMethod.apply(me, arguments);
}
};
}, this);
this._state = State.ACTIVE;
fireLifecycle('post-init', {});
},
/**
* Given a set of binder information, initialize binder instances and
* bind them to the page.
* @method attachBinders
* @private
* @param {Object} binderMap viewId ==> binder data, contains all we
* need from the mojit dispatch's meta object about all the binders
* that were executed to create the DOM addition recently added to
* the document.
* @param {string} parentId the parent binder view id to attach any
* children.
* @param {string} topLevelMojitViewId the topmost (root) binder view
* id to attach as a child to the parent.
*/
attachBinders: function(binderMap, parentId, topLevelMojitViewId) {
var context = this.context,
me = this,
newMojitProxies = [],
parent,
topLevelMojitObj,
totalBinders = Y.Object.size(binderMap),
bindersComplete = 0,
onBinderComplete,
// Note: This here so we can get access view meta data for
// each binder
store = this.resourceStore,
eventData = {
binderMap: binderMap,
parentId: parentId,
topLevelMojitViewId: topLevelMojitViewId
};
fireLifecycle('pre-attach-binders', eventData);
this.pause();
binderMap = eventData.binderMap;
parentId = eventData.parentId;
topLevelMojitViewId = eventData.topLevelMojitViewId;
Y.mojito.perf.mark('mojito', 'core_binders_start');
if (!totalBinders) {
Y.mojito.perf.mark('mojito', 'core_binders_resume');
me.resume();
Y.mojito.perf.mark('mojito', 'core_binders_end');
fireLifecycle('post-attach-binders', {});
return;
}
onBinderComplete = function() {
// only run the function when all binders have completed
bindersComplete += 1;
if (bindersComplete < totalBinders) {
return;
}
// now that all binders have been initialized and accounted
// for...
// first, we must create the MojitClient's state of the binders
// before binding, in case the binders' bind() function tries to
// do anything that includes children
Y.Array.each(newMojitProxies, function(item) {
var proxy = item.proxy,
children = item.children;
// 'me' here is the MojitoClient instance.
me._mojits[proxy._viewId] = {
proxy: proxy,
children: children
};
});
// now we'll loop through again and do the binding, saving the
// handles
Y.Array.each(newMojitProxies, function(item) {
var mojit = me._mojits[item.proxy.getId()],
proxy = item.proxy;
mojit.handles = bindNode(proxy._binder, proxy._node,
proxy._element);
});
// if there is a parent to add a child to (and a topmost child
// to add to the parent), add new top level child to parent that
// dispatched it
if (parentId && topLevelMojitViewId) {
parent = me._mojits[parentId];
topLevelMojitObj = binderMap[topLevelMojitViewId];
// this is just a shallow representation of the child, not
// the proxy object itself. but it is enough to look up the
// proxy when necessary.
if (parent && topLevelMojitObj) {
if (!parent.children) {
parent.children = {};
}
parent.children[topLevelMojitViewId] = {
type: topLevelMojitObj.type,
viewId: topLevelMojitViewId
};
}
}
Y.mojito.perf.mark('mojito', 'core_binders_resume');
me.resume();
Y.mojito.perf.mark('mojito', 'core_binders_end');
fireLifecycle('post-attach-binders', {});
};
// loop over the binder map, load, use, and instantiate them
Y.Object.each(binderMap, function(binderData, viewId) {
// Make sure viewIds's are not bound to more than once
if (me._mojits[viewId]) {
Y.log('Not rebinding binder for ' + binderData.type +
' for DOM node ' + viewId, 'info', NAME);
onBinderComplete();
return;
}
if (!binderData.name) {
Y.log('No binder for ' + binderData.type + '.' +
binderData.action, 'info', NAME);
onBinderComplete();
return;
}
YUI._mojito.loader.load(binderData.needs, function(err) {
var config,
type = binderData.type,
base = binderData.base,
binderName = binderData.name,
instanceId = binderData.instanceId,
mojitProxy,
binderClass,
children,
binder,
mojitNode,
element;
if (err) {
Y.log('failed to load prerequisites for binder ' +
binderName, 'error', NAME);
onBinderComplete();
return;
}
// "Y.mojito.binders" is blind to all new "binders" added to
// the page we have to "use()" any binder name we are given
// to have access to it.
Y.use(binderData.name, function(BY) {
// Check again to make sure viewIds's are not bound
// more than once, just in case they were bound during
// the async fetch for the binder
if (me._mojits[viewId]) {
Y.log('Not rebinding binder for ' + binderData.type +
' for DOM node ' + viewId, 'info', NAME);
onBinderComplete();
return;
}
config = Y.mojito.util.copy(binderData.config);
element = document.getElementById(viewId);
if (!element) {
Y.log('Did not find DOM node "' + viewId +
'" for binder "' + binderName + '"',
'warn', NAME);
onBinderComplete();
return;
}
mojitNode = new Y.Node(element);
// BY reference here is the 'use()' return value...the
// Binder class we need to access.
binderClass = BY.mojito.binders[binderName];
binder = Y.mojito.util.heir(binderClass);
Y.log('Created binder "' + binderName +
'" for DOM node "' + viewId + '"', 'info', NAME);
if (binderData.children) {
children = processChildren(binderData.children,
binderMap);
}
// One mojitProxy per binder. The mp is how client code
// gets to the binder...they don't hold refs to anything
// but the mp. (close enough).
mojitProxy = new Y.mojito.MojitProxy({
// private
action: binderData.action,
binder: binder,
base: base,
node: mojitNode,
element: element,
viewId: viewId,
instanceId: instanceId,
client: me,
store: store,
// public
type: type,
config: config,
context: context
});
// If client is paused, proxy must be paused
if (me._state === State.PAUSED) {
mojitProxy._pause();
}
newMojitProxies.push({
proxy: mojitProxy,
children: children
});
if (Y.Lang.isFunction(binder.init)) {
binder.init(mojitProxy);
}
onBinderComplete();
});
});
}, this);
},
/**
* Used for binders to execute their actions through the Mojito
* framework through their proxies.
* @method executeAction
* @param {Object} command must contain mojit id and action to execute.
* @param {String} viewId the view id of the current mojit, which is
* executing the action.
* @param {Function} cb callback to run when complete.
* @private
*/
executeAction: function(command, viewId, cb) {
var my = this;
// Sending a command to dispatcher that defines our action execution
Y.log('Executing "' + (command.instance.base || '@' +
command.instance.type) + '/' + command.instance.action +
'" on the client.', 'mojito', NAME);
this.resourceStore.expandInstanceForEnv('client',
command.instance, this.context, function(err, details) {
// if there is a controller in the client type details, that
// means the controller exists here "cast details.controller
// to Boolean" ;)
var existsOnClient = Boolean(details.controller);
command.context = my.context;
// if this controller does not exist here, or we have been
// instructed to force an RPC call, we'll go to the server
if (!existsOnClient || command.rpc) {
// Make the call via a fixed RPC channel
my.tunnel.rpc(command,
new Y.mojito.OutputHandler(viewId, cb, my));
} else {
// Dispatch locally
my.dispatcher.dispatch(command,
new Y.mojito.OutputHandler(viewId, cb, my));
}
});
},
doRender: function(mp, data, view, cb) {
if (!mp._views || !mp._assetsRoot) {
this.resourceStore.getType('client', mp.type, mp.context,
function(err, typeInfo) {
if (err) {
cb(new Error(
'Failed to load mojit information for ' +
mp.type
));
return;
}
mp._views = typeInfo.views;
mp._assetsRoot = typeInfo.assetsRoot;
privateRender(mp, data, view, cb);
});
} else {
privateRender(mp, data, view, cb);
}
},
doBroadcast: function(eventId, source, payload, opts) {
opts = opts || {};
var tgtInstId,
tgtViewId,
child = opts.target ?
this._mojits[source].children[opts.target.slot] : null;
if (opts && opts.target) {
if (opts.target.slot && child) {
tgtInstId = child.instanceId;
// find the target of the message
Y.Object.each(this._mojits, function(v, k) {
if (v.proxy._instanceId === tgtInstId) {
tgtViewId = k;
}
});
// if there was no target found, give an error and return
if (!tgtViewId) {
Y.log('No broadcast target found for ' +
opts.target.slot + ':' + tgtInstId, 'warn', NAME);
return;
}
} else if (opts.target.viewId) {
tgtViewId = opts.target.viewId;
}
}
if (this._listeners[eventId]) {
Y.Array.each(this._listeners[eventId], function(listener) {
if (!tgtViewId || tgtViewId === listener.viewId) {
listener.cb({
data: payload,
source: source
});
}
});
}
},
doListen: function(eventId, viewId, callback) {
if (!this._listeners[eventId]) {
this._listeners[eventId] = [];
}
this._listeners[eventId].push({
guid: viewId, // DEPRECATED, use viewId instead
viewId: viewId,
cb: callback
});
},
doUnlisten: function(viewId, needleEvent) {
var listeners = this._listeners,
eventType;
function processListenerArray(arr, id) {
var i = 0;
while (i < arr.length) {
if (arr[i].viewId === id) {
arr.splice(i, 1);
// no increment. i is now the "next" index
} else {
i += 1;
}
}
return arr;
}
// if there is only one event to unlisten, do it quickly
if (needleEvent) {
processListenerArray(listeners[needleEvent], viewId);
} else {
// but if we need to unlisten to all callbacks registered by
// this binder, we must loop over the entire listener object
for (eventType in listeners) {
if (listeners.hasOwnProperty(eventType)) {
processListenerArray(listeners[eventType], viewId);
}
}
}
},
destroyMojitProxy: function(id, retainNode) {
var parent;
if (this._mojits[id]) {
// TODO: activate call to unbindNode below:
// unbindNode(this._mojits[id].proxy._binder,
// this._mojits[id].handles);
this._mojits[id].proxy._destroy(retainNode);
delete this._mojits[id];
// We don't manage binder children automatically, but any time a
// new child is added or removed, we should at least give the
// application code a chance to stay up to date if they want to.
// The only gap is when a mojit destroys itself.
// onChildDestroyed is called whenever a binder is destroyed so
// any parents can be notified.
parent = findParentProxy(this._mojits, id);
if (parent && parent._binder.onChildDestroyed &&
Y.Lang.isFunction(parent._binder.onChildDestroyed)) {
parent._binder.onChildDestroyed({ id: id });
}
}
},
/**
* Pause the Mojito Client and all mojits that are running. This will
* notify all binders that they have been paused by calling their
* onPause() functions. It will prevent the immediate execution of
* several mojit proxy operations that might cause a long process to
* begin (especially things that might go to the server).
*
* To resume, simply call .resume(). This will immediately execute all
* actions that occurred while Mojito was paused.
* @method pause
*/
pause: function() {
if (this._state === State.PAUSED) {
Y.log('Cannot "pause" the mojito client because it has' +
' already been paused.', 'warn', NAME);
return;
}
this._state = State.PAUSED;
Y.Object.each(this._mojits, function(moj) {
moj.proxy._pause();
});
Y.log('Mojito Client state: ' + this._state + '.', 'info', NAME);
},
/**
* Resumes the Mojito client after it has been paused (see method
* "pause"). If there are any queued actions that were executed and
* cached during the pause, calling resume() will immediately execute
* them. All binders are notified through their onResume() function that
* they are been resumed.
* @method resume
*/
resume: function() {
if (this._state !== State.PAUSED) {
Y.log('Cannot "resume" the mojito client because it was' +
' never paused.', 'warn', NAME);
return;
}
this._state = State.ACTIVE;
Y.Object.each(this._mojits, function(moj) {
moj.proxy._resume();
});
Y.Array.each(this._pauseQueue, function(queuedItem) {
var fn = queuedItem.fn,
args = queuedItem.args;
fn.apply(this, args);
}, this);
this._pauseQueue = [];
Y.log('Mojito Client state: ' + this._state + '.', 'info', NAME);
},
refreshMojitView: function(mp, opts, cb) {
var my = this;
mp.invoke(mp._action, opts, function(err, data, meta) {
if (err) {
if (typeof cb === 'function') {
cb(new Error(err));
return;
} else {
throw new Error(err);
}
}
/*
* The new markup returned from the server has all new DOM ids
* within it, but we don't want to use them. Before doing any
* DOM stuff, we are going to replace all the new view ids with
* our current view ids for this mojit view as well as any
* children that have come along for the ride.
*/
var idReplacements = {}, // from: to
metaBinderViewId,
mBinder,
freshBinders = {},
clientMojitViewId,
clientMojit,
processMojitChildrenForIdReplacements;
/*
* Recursive function used to walk down the hierarchy of
* children in order to replace every view id within the meta
* data
*/
processMojitChildrenForIdReplacements =
function(clientChildren, metaChildren, idRepls) {
var metaChild,
childMojitProxy,
metaSubChildren,
slot;
if (!metaChildren || !clientChildren) {
return;
}
for (slot in metaChildren) {
if (metaChildren.hasOwnProperty(slot)) {
metaChild = metaChildren[slot];
if (clientChildren && clientChildren[slot]) {
childMojitProxy =
clientChildren[slot].proxy;
}
if (childMojitProxy) {
metaSubChildren = meta.binders[
metaChild.viewId
].config.children;
idRepls[metaChild.viewId] =
childMojitProxy.getId();
if (metaSubChildren) {
processMojitChildrenForIdReplacements(
my.mojits[childMojitProxy.getId()].
children,
metaSubChildren,
idRepls
);
}
}
}
}
};
for (clientMojitViewId in my._mojits) {
if (my._mojits.hasOwnProperty(clientMojitViewId)) {
clientMojit = my._mojits[clientMojitViewId];
for (metaBinderViewId in meta.binders) {
if (meta.binders.hasOwnProperty(metaBinderViewId)) {
mBinder = meta.binders[metaBinderViewId];
if (mBinder.instanceId ===
clientMojit.proxy._instanceId) {
Y.log('matched instanceId ' +
mBinder.instanceId,
'debug',
NAME
);
idReplacements[metaBinderViewId] =
clientMojitViewId;
processMojitChildrenForIdReplacements(
my._mojits[clientMojit.proxy.getId()].
children,
mBinder.children,
idReplacements
);
}
}
}
}
}
Y.Object.each(idReplacements, function(to, from) {
var regex = new RegExp(from, 'g');
data = data.replace(regex, to);