forked from selsamman/amorphic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
841 lines (662 loc) · 29.9 KB
/
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
/* Copyright 2012-2013 Sam Elsamman
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
RemoteObjectTemplate._injectIntoTemplate = function (template) {
// Add persistors to foreign key references
var schema = amorphic.schema[template.__name__] || {};
template._injectProperties = function () {
var props = template.getProperties();
for (var prop in props) {
var defineProperty = props[prop];
if (defineProperty.autoFetch || schema[prop]) {
(function () {
var closureProp = prop;
var closureDefineProperty = defineProperty;
if (!props[closureProp + 'Persistor']) {
template.createProperty(closureProp + 'Persistor', {type: Object, toServer: false,
value:{isFetched: !defineProperty.autoFetch, isFetching: false}});
}
if (!template.prototype[closureProp + 'Fetch']) {
template.createProperty(closureProp + 'Fetch', {on: 'server', body: function () {}});
}
if (!template.prototype[closureProp + 'Get']) {
template.createProperty(closureProp + 'Get', {on: 'client', body: function () {
var persistor = this[closureProp + 'Persistor'];
if ((persistor.isFetched == false) && !persistor.isFetching) {
persistor.isFetching = true;
if (closureDefineProperty.type == Array) {
this[closureProp] = [];
}
this[closureProp + 'Fetch'].call(this);
}
return this[closureProp];
}});
}
})();
}
}
};
if (template.defineProperties) {
template._injectProperties();
}
};
var module = {exports: {}};
amorphic = // Needs to be global to make mocha tests work
{
performanceLogging: {
start: (new Date()).getTime(),
tasks: [],
addCompletedTask: function (taskName) {
this.tasks.push({name: taskName, time: (new Date()).getTime()});
},
getData: function () {
var data = {start: this.start, duration: (new Date()).getTime() - this.start, tasks: []};
if (this.tasks.length === 0) {
return null;
}
var start = this.start;
for (var ix = 0; ix < this.tasks.length; ++ix) {
data.tasks.push({name: this.tasks[ix].name, duration: this.tasks[ix].time - start});
start = this.tasks[ix].time;
}
this.startTasks();
return data;
},
startTasks: function (time) {
this.start = time || (new Date()).getTime();
this.tasks = [];
}
},
initializationData: {},
lastServerInteraction: (new Date()).getTime(),
setInitialMessage: function (message) {
this.initializationData = message;
},
setConfig: function (config) {
this.config = config;
RemoteObjectTemplate.config = {nconf: {get: get}};
function get (key) {
return config[key];
}
},
setSchema: function (schema) {
this.schema = schema;
},
setApplication: function(app) {
this.app = app;
},
maxAlerts: 5,
shutdown: false,
sequence: 1,
logLevel: 1,
rootId: null,
config: {},
schema: {},
sessionExpiration: 0,
sessionExpirationCushion: 10000,
heartBeat: null,
session: (new Date()).getTime(),
state: 'live',
app: 'generic',
sessionId: 0,
loggingContext: {},
/**
* start a session with the server and process any initial messages
*
* @param url - of the semotus message handler (usually /semotus)
* @param rootCallback - callback that will passed the root object
* @param renderCallback - callback to render UI changes upon receipt of message
*
*/
establishClientSession: function(controllerTemplate, appVersion, bindController, refresh, reload, offline) {
this.performanceLogging.addCompletedTask('Starting establishClientSession');
this.setCookie('session' + this.app, this.session, 0);
// Initialize object
if (appVersion == '0') {
appVersion = null;
}
this.url = this.initializationData.url;
this.sessionExpiration = this.initializationData.message.sessionExpiration;
this.bindController = bindController;
this.appVersion = appVersion;
this.reload = reload;
this.offline = offline;
this.refresh = refresh;
this.sequence = 1;
this.importTemplates();
this.performanceLogging.addCompletedTask('Templates Compiled in browser');
// Grab the controller template which is not visible until after importTemplates
this.controllerTemplate = window[controllerTemplate];
if (!this.controllerTemplate) {
alert("Can't find " + controllerTemplate);
return;
}
this.sendLoggingMessage = function (level, data) {
var message = {type: 'logging', loggingLevel: level, loggingContext: this.loggingContext, loggingData: data};
this.loggingContext = {};
this._post(self.url, message);
};
RemoteObjectTemplate.logger.sendToLog = function (level, data) {
var output = RemoteObjectTemplate.logger.prettyPrint(level, data);
console.log(output);
if (level == 'error' || level == 'fatal') {
this.sendLoggingMessage(level, data);
if (this.controller && typeof(this.controller.displayError) === 'function') {
this.controller.displayError(output);
}
}
}.bind(this);
this.setContextProps = RemoteObjectTemplate.logger.setContextProps;
RemoteObjectTemplate.logger.setContextProps = function (props) {
for (var prop in props) {
this.loggingContext[prop] = props[prop];
}
this.setContextProps.call(RemoteObjectTemplate.logger, props);
}.bind(this);
/**
* Send message to server and process response
*
* @param message
*/
var self = this;
this.sendMessage = function (message) {
message.sequence = self.sequence++;
message.loggingContext = self.loggingContext;
message.performanceLogging = self.performanceLogging.getData();
self.loggingContext = {};
// Sending rootId will reset the server
if (self.rootId) {
message.rootId = self.rootId;
self.rootId = null;
console.log('Forcing new controller on server');
}
if (self.logLevel > 0) {
console.log ('sending ' + message.type + ' ' + message.name);
}
self.lastServerInteraction = (new Date()).getTime();
// Post xhr to server
RemoteObjectTemplate.enableSendMessage(false); // Queue stuff while we are out to the server
self._post(self.url, message, function (request) { // Success
RemoteObjectTemplate.enableSendMessage(true, this.sendMessage); // Re-enable sending
var message = JSON.parse(request.responseText);
if (self.logLevel > 0) {
console.log('receiving ' + message.type + ' ' + message.name + ' serverAppVersion=' + message.ver +
'executionTime=' + ((new Date()).getTime() - self.lastServerInteraction) +
'ms messageSize=' + Math.round(request.responseText.length / 1000) + 'K');
}
// If app version in message not uptodate
if (self.appVersion && message.ver != self.appVersion) {
console.log('Application version ' + self.appVersion + ' out of date - ' + message.ver + ' is available - reloading in 5 seconds');
self.shutdown = true;
self.reload();
return;
}
// Setup a new session timeout check
self._setSessionTimeout();
if (message.type == 'pinged') {
return;
}
if (message.sessionExpired) {
RemoteObjectTemplate.clearPendingCalls();
}
// Handle resets and refreshes
if (message.newSession || message.type == 'refresh') {
self._reset(message);
}
else {
var hasChanges = RemoteObjectTemplate.processMessage(message);
Q.delay(50).then(function () {
self.refresh(hasChanges);
}); // Let the promises settle out
}
if (message.sync === false) {
self.refreshSession();
}
}, function (err) { // Failure of the wire
RemoteObjectTemplate.enableSendMessage(true, this.sendMessage); // Re-enable sending
if (typeof(self.offline) === 'function') {
self.offline.call();
}
else if (--self.maxAlerts > 0) {
alert('Error on server: ' + err);
}
});
};
// Kick everything off by processing initial message
this._reset(this.initializationData.message, appVersion, reload);
this.performanceLogging.addCompletedTask('Initial Message Processed on Browser');
// Manage events for session expiration
this.addEvent(document.body, 'click', function() {
self._windowActivity(); self.activity = true;
});
this.addEvent(document.body, 'mousemove', function() {
self._windowActivity(); self.activity = true;
});
this.addEvent(window, 'focus', function () {
self._windowActivity();
});
setInterval(function () {
self._zombieCheck();
}, 50);
// For file uploads we use an iFrame
},
prepareFileUpload: function(id) {
var iFrame = document.getElementById(id);
var iFrameDoc = iFrame.contentWindow.document;
var content = document.getElementById(id + '_content').value;
iFrameDoc.open();
iFrameDoc.write(content.replace(/__url__/, this.url + '&file=yes'));
iFrameDoc.close();
},
// When a zombie gets focus it wakes up. Pushing it's cookie makes other live windows into zombies
_windowActivity: function () {
if (this.state == 'zombie') {
this.expireController(); // Toss anything that might have happened
RemoteObjectTemplate.enableSendMessage(true, this.sendMessage); // Re-enable sending
this.state = 'live';
this.rootId = null; // Cancel forcing our controller on server
this.refreshSession();
console.log('Getting live again - fetching state from server');
}
this.setCookie('session' + this.app, this.session, 0);
},
// Anytime we see some other windows session has been stored we become a zombie
_zombieCheck: function () {
if (RemoteObjectTemplate.getPendingCallCount() == 0 && this.getCookie('session' + this.app) != this.session) {
if (this.state != 'zombie') {
this.state = 'zombie';
this.expireController();
RemoteObjectTemplate.enableSendMessage(false); // Queue stuff as a zombie we will toss it later
console.log('Another browser took over, entering zombie state');
}
}
},
/**
* Manage session expiration by listening for 'activity' and pinging the
* the server just before the session expires
*/
_setSessionTimeout: function () {
var self = this;
self.activity = false;
if (self.heartBeat) {
clearTimeout(self.heartBeat);
}
self.heartBeat = setTimeout(function () {
if (self.state == 'live') {
if (self.activity) {
console.log('Server session ready to expire, activity detected, keeping alive');
self.pingSession(); // Will setup new timer
}
else if (self.controller.clientExpire && this.controller.clientExpire()) { // See if expiration handled by controller
console.log('Server session ready to expire, controller resetting itself to be offline');
return; // No new timer
}
else {
console.log('Server session ready to expire, resetting controller to be offline');
self.expireController();
}
}
}, self.sessionExpiration - self.sessionExpirationCushion);
},
expireController: function () {
// Create new controller
if (this.sessionId) {
RemoteObjectTemplate.deleteSession(this.sessionId);
}
this.sessionId = RemoteObjectTemplate.createSession('client', this.sendMessage);
this.controller = new (this.controllerTemplate)();
this.rootId = this.controller.__id__; // Force it to be sent as reset on next message
RemoteObjectTemplate.controller = this.controller;
RemoteObjectTemplate.syncSession(); // Start tracking changes post init
this.bindController.call(null, this.controller, this.sessionExpiration); // rebind to app
},
pingSession: function () {
this.sendMessage({type: 'ping'});
},
resetSession: function () {
this.sendMessage({type: 'reset'});
},
refreshSession: function () {
this.sendMessage({type: 'refresh'});
},
setNewController: function (controller, expiration) {
this.rootId = controller.__id__;
this.bindController.call(null, controller, expiration);
},
_reset: function (message, appVersion, reload) {
if (this.sessionId) {
RemoteObjectTemplate.deleteSession(this.sessionId);
}
this.sessionId = RemoteObjectTemplate.createSession('client', this.sendMessage);
RemoteObjectTemplate.setMinimumSequence(message.startingSequence);
if (message.rootId) {
this.controller = RemoteObjectTemplate._createEmptyObject(this.controllerTemplate, message.rootId);
}
else {
this.controller = new (this.controllerTemplate)();
this.rootId = this.controller.__id__;
}
RemoteObjectTemplate.controller = this.controller;
if (appVersion && message.ver != appVersion) {
console.log('Application version ' + appVersion + ' out of date - ' + message.ver + ' is available - reloading in 5 seconds');
this.shutdown = true;
this.bindController.call(null, this.controller, message.sessionExpiration);
reload();
return;
}
RemoteObjectTemplate.syncSession();
RemoteObjectTemplate.processMessage(message);
this.bindController.call(null, this.controller, message.sessionExpiration);
},
_post: function (url, message, success, failure, retries, retryInterval) {
success = success || function () {};
failure = failure || function () {};
retries = retries || 30;
retryInterval = retryInterval || 2000;
if (this.shutdown) {
return;
}
var request = this.getxhr();
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/json');
var self = this;
request.onreadystatechange = function () {
if (request.readyState != 4) {
return;
}
try {
var status = request.status;
var statusText = request.statusText;
}
catch (e) {
var status = 666;
var statusText = 'unknown';
}
if (status == 200 || status == 0) {
if (this.logLevel > 0) {
console.log('Got response for: ' + message.type + ' ' + message.name);
}
success.call(this, request);
}
else {
console.log('Error: ' + message.type + ' ' + message.name + ' status: ' + status + ' - ' + statusText);
if (status == 503 && --retries) {
console.log('temporary error retrying in ' + retryInterval / 1000 + ' seconds');
setTimeout(function () {
return self._post(url, message, success, failure, retries, retryInterval);
}, retryInterval);
}
else {
failure.call(this, status + ' - ' + statusText);
}
}
};
try {
request.send(JSON.stringify(message));
}
catch (e) {
throw 'xhr error ' + e.message + ' on ' + url;
}
},
getxhr: function() {
try {
return new XMLHttpRequest();
}
catch (e) {
try {
return new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e2) {
try {
return new ActiveXObject('Microsoft.XMLHTTP');
}
catch (e3) {
throw 'No support for XMLHTTP';
}
}
}
},
/**
* Import templates by calling each property of exports, dividing them into two rounds
* and starting with the non _mixin
*/
importTemplates: function () {
RemoteObjectTemplate.lazyTemplateLoad = this.config.lazyTemplateLoad;
// Graph of mixins so we can process them at the end
var mixinGraph = {};
if (module.exports.objectTemplateInitialize) {
module.exports.objectTemplateInitialize(RemoteObjectTemplate);
}
var objectTemplateSubClass = Object.create(RemoteObjectTemplate);
var currentContext = {pass: 1};
if (this.config.templateMode == 'typescript') {
}
else if (this.config.templateMode == 'auto') {
var deferredExtends = [];
RemoteObjectTemplate.__statics__ = {};
usesV2ReturnPass1.prototype.mixin = function () {};
usesV2ReturnPass1.prototype.extend = function(name) {
this.extendedName = name;
deferredExtends.push(this);
return new usesV2ReturnPass1(name);
};
usesV2ReturnPass1.prototype.doExtend = function(futureTemplates) {
if (!RemoteObjectTemplate.__dictionary__[this.baseName]) {
if (futureTemplates[this.baseName]) {
futureTemplates[this.baseName].doExtend(futureTemplates);
}
if (!RemoteObjectTemplate.__dictionary__[this.baseName]) {
throw Error('Attempt to extend ' + this.baseName + ' which was never defined; extendedName=' + this.extendedName);
}
}
if (!RemoteObjectTemplate.__dictionary__[this.extendedName]) {
var template = RemoteObjectTemplate.__dictionary__[this.baseName].extend(this.extendedName, {});
}
};
for (var exp in module.exports || {}) {
if (!exp.match(/_mixins/)) {
objectTemplateSubClass.create = function (name) {
var template = RemoteObjectTemplate.create(name, {});
var originalExtend = template.extend;
template.extend = function (name, props) {
var template = RemoteObjectTemplate.__dictionary__[name];
if (template) {
template.mixin(props);
}
else {
template = originalExtend.call(this, name, props);
}
return template;
};
var originalMixin = template.mixin;
template.mixin = function () {
if (currentContext.pass === 2) {
if (arguments[0] && arguments[0].isObjectTemplate) {
scheduleDeferredMixinProcessing(template, arguments[0]);
}
else {
originalMixin.apply(template, arguments);
}
}
};
return template;
};
var initializerReturnValues = (module.exports[exp])(objectTemplateSubClass, usesV2Pass1);
recordStatics(initializerReturnValues);
}
}
// Extended classes can't be processed until now when we know we have all the base classes defined
var futureTemplates = {};
for (var ix = 0; ix < deferredExtends.length; ++ix) {
futureTemplates[deferredExtends[ix].extendedName] = deferredExtends[ix];
}
for (var ix = 0; ix < deferredExtends.length; ++ix) {
deferredExtends[ix].doExtend(futureTemplates);
}
currentContext.pass = 2;
var objectTemplateSubClass = Object.create(RemoteObjectTemplate);
for (var exp in module.exports) {
objectTemplateSubClass.create = function (name, props) {
if (RemoteObjectTemplate.__dictionary__[name.name || name]) {
RemoteObjectTemplate.__dictionary__[name.name || name].mixin(props);
}
else {
RemoteObjectTemplate.create(name, props);
}
return RemoteObjectTemplate.__dictionary__[name.name || name];
};
var initializerReturnValues;
if (this.config && this.config.modules) {
initializerReturnValues = (module.exports[exp])(objectTemplateSubClass, usesV2Pass2, this.config.modules[exp.replace(/_mixins/, '')]);
}
else {
initializerReturnValues = (module.exports[exp])(objectTemplateSubClass, usesV2Pass2, null);
}
recordStatics(initializerReturnValues);
}
processDeferredMixins();
for (var name in RemoteObjectTemplate.__dictionary__) {
window[name] = RemoteObjectTemplate.__dictionary__[name];
}
for (var name in RemoteObjectTemplate.__statics__) {
window[name] = RemoteObjectTemplate.__statics__[name];
}
}
else {
var requires = {};
for (var exp in module.exports || {}) {
if (!exp.match(/_mixins/)) {
var templates = (module.exports[exp])(RemoteObjectTemplate, function () {
return window;
});
requires[exp] = templates;
for (var template in templates) {
window[template] = templates[template];
}
}
}
var templates = flatten(requires);
for (var exp in module.exports) {
if (exp.match(/_mixins/)) {
if (this.config) {
templates = (module.exports[exp])(RemoteObjectTemplate, requires, this.config.modules[exp.replace(/_mixins/, '')], templates);
}
else {
templates = (module.exports[exp])(RemoteObjectTemplate, requires, null, templates);
}
for (var template in templates) {
window[template] = templates[template];
}
}
}
}
RemoteObjectTemplate.performInjections();
function flatten (requires) {
var classes = {};
for (var f in requires) {
for (var c in requires[f]) {
classes[c] = requires[f][c];
}
}
return classes;
}
function usesV2Pass1 (file, templateName, options) {
var templateName = templateName || file.replace(/\.js$/, '').replace(/.*?[\/\\](\w)$/, '$1');
var staticTemplate = RemoteObjectTemplate.__statics__[templateName];
return staticTemplate || new usesV2ReturnPass1(templateName);
}
function usesV2Pass2 (file, templateName, options) {
var templateName = templateName || file.replace(/\.js$/, '').replace(/.*?[\/\\](\w)$/, '$1');
return RemoteObjectTemplate.__dictionary__[templateName] || RemoteObjectTemplate.__statics__[templateName];
}
// An object for creating request to extend classes to be done at thend of V2 pass1
function usesV2ReturnPass1 (base) {
this.baseName = base;
}
function scheduleDeferredMixinProcessing(template, mixinTemplate) {
mixinGraph[template.__name__] = mixinGraph[template.__name__] || {};
mixinGraph[template.__name__][mixinTemplate.__name__] = true;
}
function processDeferredMixins() {
// Go through each template that needs a mixin
for (var rootMixin in mixinGraph) {
processRootMixin(mixinGraph[rootMixin], rootMixin);
}
function processRootMixin(rootMixin, rootMixinTemplateName) {
// Go through each of the templates that needs to be mixed in
for (var childMixin in rootMixin) {
processChildMixin(childMixin);
}
function processChildMixin(childMixinTemplateName) {
// that template that needs to be mixed in also needs mixins, process them first
if (mixinGraph[childMixinTemplateName]) {
processRootMixin(mixinGraph[childMixinTemplateName], childMixinTemplateName);
mixinGraph[childMixinTemplateName] = {}; // Make sure we don't process twice
}
// Now we can safely do the mixin
RemoteObjectTemplate.mixin(RemoteObjectTemplate.__dictionary__[rootMixinTemplateName],
RemoteObjectTemplate.__dictionary__[childMixinTemplateName]);
}
}
}
function recordStatics(initializerReturnValues) {
for (var returnVariable in initializerReturnValues) {
if (!RemoteObjectTemplate.__dictionary__[returnVariable]) {
if (RemoteObjectTemplate.__statics__[returnVariable]) {
var staticProps = Object.getOwnPropertyNames(RemoteObjectTemplate.__statics__[returnVariable]);
for (var sx = 0; sx < staticProps.length; ++sx) {
RemoteObjectTemplate.__statics__[returnVariable][staticProps[sx]] =
initializerReturnValues[returnVariable][staticProps[sx]];
}
}
else {
RemoteObjectTemplate.__statics__[returnVariable] = initializerReturnValues[returnVariable];
}
}
}
}
},
addEvent: function (elem, evName, evFunc) {
if (elem.attachEvent) {
elem.attachEvent('on' + evName, function() {
evFunc.call(elem);
});
}
else {
elem.addEventListener(evName, evFunc, false);
}
},
getCookie: function (str) {
return this.getCookieJar()[str] || '';
},
setCookie: function (cookie, value, length) {
var now = new Date();
now.setDate(now.getDate() + (length ? length : 30));
document.cookie = cookie + '=' + value + '; expires=' + now.toUTCString() + '; path=/';
},
getCookieJar: function () {
var cookies = document.cookie.split(';');
var jar = new Object();
for (var i = 0; i < cookies.length; ++i) {
if (cookies[i].match(/[ ]*(.*?)=(.*)/)) {
jar[RegExp.$1] = RegExp.$2;
}
}
return jar;
}
};