-
Notifications
You must be signed in to change notification settings - Fork 0
/
idom.js
1986 lines (1252 loc) · 54.4 KB
/
idom.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
/*! idi.bidi.dom
*
*
* idom v0.17
*
* Key-value JSON API for template-based HTML view compositing
*
*
* ****************************************************************************
*
* Copyright (c) Marc Fawzi, Deep Thought, Inc. 2012
*
* http://javacrypt.wordpress.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* *****************************************************************************
*
* Some portions are derived from NattyJS, an early precursor by the same author
* "Copyright (c) Marc Fawzi, NiNu, Inc. 2011-2012" published under BSD License.
*
*/
/******************************************************************************
*
* README:
*
* This version should work in all recent versions of the major browsers
*
* idi.bidi.dom - Anti-Templating Framework For Javascript -- offers a new and
* different way for interacting with the DOM. In abstract terms, it takes the DOM
* and adds variables, scope, variable memoization, multiple-inheritance and
* type polymorphism (with the Node Prototype as the user defined type) In logical
* terms, it offers a flat JSON API for creating, populating, and de-populating
* predetermined DOM structures with the ability to link, directly access, populate
* and de-populate other such DOM structures at any depth within them. It gives us
* a simpler alternative to the browser's hierarchical DOM manipulation API while
* allowing us to reduce the amount of HTML as well as separate the HTML from the
* presentation logic.
*
* Why use it?
*
* idi.bidi.dom reduces HTML on a page to a minimum and places a simple and consistent
* JSON API between presentation logic and the DOM
*
* What does it do?
*
* idi.bidi.dom allows the DOM to be decomposed into Nodes each having a Node Prototype
* with data-injected variables in their markup. Multiple instances of each Node (i.e.
* data populated versions, each with its own persisted data) may be created, populated
* with data, and inserted into --or deleted from-- the Node (with the ability to target
* specific, previously inserted instances of the Node or all such instances). Each Node
* may embed any number of other Nodes, at any depth within its Node Prototype's markup.
*
* Additionally, idi.bidi.dom allows us to clone populated Nodes to create copies of the
* Node (and any Linked Nodes within it) which can be re-populated and de-populated in
* direct fashion.
*
* Usage:
*
* format: document.querySelector('#someNode').idom$(data [, settings])
*
* output: creates a new instance of the Node using 'data' (json) to populate the
* special variables in the Node, then after/before to (or replace) existing
* instance(s) of the Node
*
* forClone: id of the clone the data being populated is intended for. This is omitted
* when operating on cloned nodes
*
* data: {key: value, key: value, key: value, etc}
* where the key must match the variable name in the data minus the idom$ prefix
*
* settings: {mode: 'replace'|'after'|'before'|'node'|'proto', targetInstanceName:
* value, instanceName: value} ... replace is default mode
*
* if there are no populated instances of the Node then after/before/replace will create
* a new instance of the Node (so if a targetInstanceName is supplied in this case it will
* throw an error, so call .$isPopulated() first to be sure before invoking this method with
* targetInstanceName, unless you know the node is populated)
*
* If 'mode' is set to 'node' in settings then no other settings param is expected
* and only the node's attributes are populated. Setting mode to 'node' will cause idom
* to populate only the attributes in the node itself and does not create any populated
* instances of its node prototype. idom also offers a way to populate just the attributes
* of each node instance by setting mode to 'proto' and specifying targetInstanceName or none
* for all node instances in a given node. Both 'proto' and 'node' modes may be useful when
* working with the node attributes or the node instance attributes where a jQuery plugin/
* widget is instantiated (after caching) on a given node instance.
*
* targetInstanceName: (1) idom-instance-name value for the instance of the Node to insert at
* in after and before modes. If null, insert after/before the last/first previously populated
* instance of the Node, or as the first instance if none were previously populated.
*
* targetInstanceName: (2) dom-instance-name value for instance(s) of the Node Protoype to
* replace when in replace mode. If null, replace all instances.
*
* instanceName: idom-instance-name value for instance of Prototype Node being populated.
*
*********************************************************************************
*
* Other idom methods are
*
* .idom$dePopulate([settings]) which can delete certain populated instances of the Node
* Prototype or all populated instances
*
* .idom$isPopulated() may be queried before specifying targetInstanceName to verify the
* existence of populated instance(s) of the node prototype (the targets)
*
* idom$clone may be used to clone an entire node (including any linked nodes) after it's
* been populated)
*
* idom.eventHandler may be used to defined inline events, e.g. onclick=idom$someHandler
* and setting someHandler to idom.eventHandler(event, this, someFunction) during instance
* creation which binds 'this' context to the element the event was triggered on and passes
* the event, parent node id for the instance, and the instanceName
*
* idom.baseSelector maybe used on node and instance id's to strip out the clone and any link
* references from instanceName which is
*
**********************************************************************************
*
* About Events:
*
* If a handler is defined on the node it will only have access to the node id. If it's
* defined on or in the node prototype it will have access to the instance id
*
* The context of 'this' inside the handler function is the element the event is
* defined on
*
* Event handlers that are NOT defined using inline event handlers (like onclick,
* onmouseover, etc) are not handled by idom at this time.
*
*
*********************************************************************************/
(function() {
_$ = function(selector) {
return document.querySelector(selector);
}
_$$ = function(selector) {
return document.querySelectorAll(selector);
}
// define the global idom object
idom = {};
// user defined iteration and DOM traversal functions should be added to idom.user
// Example: idom.user.someFunction = function () { ... }
idom.user = {};
idom.internal = {};
idom.utils = {};
// define regular expression (RegEx) pattern for Prototype variables. use idom$ since that can't be confused
idom.regex = /(idom\$\w+)/g;
// define length of Prototype variables pattern
idom.regexLength = 5;
// data caches
idomData = {};
idomData.cache = {};
idomData.nodeCache = {};
idomData.instanceCache = {};
// internal use
idomDOM = {};
idomDOM.cache = {};
idomDOM.nodeAttributes = {};
idomDOM.instanceAttributes = {};
idomDOM.nodeShell = {};
// init method to be called from window.onload or $(document).ready
idom.cache = function() {
// re-cache()'ing must be avoided as the DOM will have changed,
// which would cause the cached templates to be out of sync
// with the DOM
if (idomDOM.cacheDone) {
return;
}
// basic browser compatibility test
if (!Element ||
!NodeList ||
!("outerHTML" in document.createElementNS("http://www.w3.org/1999/xhtml", "_")) ||
!("innerHTML" in document.createElementNS("http://www.w3.org/1999/xhtml", "_")) ||
typeof document.querySelector == 'undefined' ||
typeof document.querySelectorAll == 'undefined' ||
typeof Object.keys == 'undefined' ||
typeof JSON == 'undefined'
) {
var err = new Error;
err.message = "Browser is not supported: some basic browser objects, methods or properties are missing: \n" +
"!Element || \n" +
"!NodeList || \n" +
"!('outerHTML' in document.createElementNS('http://www.w3.org/1999/xhtml', '_')) ||\n" +
"!('innerHTML' in document.createElementNS('http://www.w3.org/1999/xhtml', '_')) ||\n" +
"typeof document.querySelector == 'undefined' ||\n" +
"typeof document.querySelectorAll == 'undefined' ||\n" +
"typeof Object.keys == 'undefined' ||\n" +
"typeof JSON == 'undefined'\n"
throw err.message + '\n' + err.stack;
}
// fetch all elements with idom-node-id (no need to loop thru script tags)
var els = document.querySelectorAll('[idom-node-id]');
var elCount, elem;
// nodelist
if (els[0]) {
elCount = els.length;
// element
} else if (typeof els.style != 'undefined') {
elCount = 1;
elem = els;
// none
} else {
elCount = 0;
}
for (var n = 0; n < elCount; n++) {
el = elem || els[n];
var nid = el.getAttribute('idom-node-id');
if (!nid) {
var err = new Error;
err.message = "Node must have idom-node-id attribute set to a non-empty string value"
throw err.message + '\n' + getPathTo(el)
}
if (nid.match(idom.regex)) {
var err = new Error;
err.message = "idom-node-id must not contain a special variable. "
throw err.message + '\n' + getPathTo(el)
}
if (nid.indexOf('@') != -1) {
var err = new Error;
err.message = "idom-node-id must not contain special character @ at time of caching"
throw err.message + '\n' + getPathTo(el)
}
if (idomDOM.cache[nid]) {
var err = new Error;
err.message = "idom-node-id is in use by another Node"
throw err.message + '\n' + getPathTo(el)
}
if (el.tagName.toLowerCase() == "iframe") {
var err = new Error;
err.message = "iframe is not supported as Node. You must load and use idom from within the iframe"
throw err.message + '\n' + getPathTo(el)
}
if (typeof el.outerHTML == 'undefined' || typeof el.innerHTML == 'undefined') {
var err = new Error;
err.message = "this element type is not supported by idom"
throw err.message + '\n' + getPathTo(el)
}
if (el.children.length != 1) {
var err = new Error;
err.message = "At the time of caching, node must contain just one child element as the Node Prototype." +
"You may use any block level element and encapsulate other elements within it."
throw err.message + '\n' + getPathTo(el)
}
if (Object.keys(el).join(",").match("(jQuery)") || Object.keys(el.children[0]).join(",").match("(jQuery)")) {
var err = new Error;
err.message = "Cannot instantiate jQuery object on an idom node or node prototype.\n" +
"The right way is to instntiate jQuery plugin/jQuery UI widget on a populated node instance in a cloned node\n" +
"and use 'node' mode to populate the attributes of the containing node or 'proto' mode to populate the node\n" +
"instance, e.g. by adding 'idom-style' in-line CSS style text with idom$ variables to override the jQuery added\n" +
"CSS classes "
throw err.message + '\n' + getPathTo(el)
}
var commentNodes = getElementsByNodeType(el, 8);
if (commentNodes.length) {
for (var i = 0; i < commentNodes.length; i++) {
if (commentNodes[i].textContent.match(/(@idom)([\s+])(\w+)/)) {
var err = new Error;
err.message = "@idom linked nodes must be placed inside the Node Prototype (the direct child of the Node)"
throw err.message + '\n' + getPathTo(el)
}
// remove comments from cached copy of template
el.removeChild(commentNodes[i])
}
}
if (el.innerHTML.match(/(idom-node-id)/)) {
var err = new Error;
err.message = "node must not have any descendants with idom-node-id at time of caching\n" +
"you may dynamically link-in other Nodes by inserting <!-- @idom [the idom-node-id for node you wish to nest without the brackets] --> anywhere inside the Node Prototype"
throw err.message + '\n' + getPathTo(el)
}
// using 'id' is problematic when the node gets linked and/or cloned as you'll have duplicate id's. idom deals with this by
// changing the idom-node-id and idom-instance-name's attribute in Linked Nodes inside the host Node Prototype by adding the
// link and clone reference
if (el.outerHTML.match(/([ ])(id)([ ]+|)(\=)/)) {
var err = new Error;
err.message = "node should not have an 'id' attribute anywhere within its HTML (to query the DOM for the element, you may use document.querySelector with\n" +
"'[idom-node-id=\"someString\"]' or, for populated node instances, with '[idom-instance-id=\"someString\"]'"
throw err.message + '\n' + getPathTo(el)
}
if (el.outerHTML.match("(idom-instance-name)")) {
var err = new Error;
err.message = "idom-instance-name is not expected at time of caching (it's added automatically when node prototype instances are created)"
throw err.message + '\n' + getPathTo(el)
}
var outerOnly = el.outerHTML.replace(el.innerHTML, "");
// lookbehind in Javascript RegExp
if (outerOnly.replace("idom-node-id=", "").match(/^(?:(?!([\s\n\r]{1,})idom-\w+([ ]{0,})=([ ]{0,})(\w+|\"|\')).)*\w+([ ]{0,})=([ ]{0,})(\w+|\"|\')/)) {
var err = new Error;
err.message = "you must prefix all in-line attributes with 'idom-' (incl. any class, style data- attributes and inline events)\n" +
"The non-prefixed attributes will be generated automatically after the idom-prefixed attributes are populated (this\n" +
"is to get around the IE 'style' issue"
throw err.message + '\n' + '\n' + getPathTo(el)
}
// implements the above for nested elements
checkAttributes(el);
// cache the virgin innerHTML of node
idomDOM.cache[nid] = el.innerHTML;
// cache the virgin outerHTML of node (minus the innerHTML)
idomDOM.nodeShell[nid] = outerOnly;
// cache the node attributes
for (var i = 0; i < el.attributes.length; i++) {
var attrib = el.attributes[i];
if (attrib.specified == true &&
attrib.name != 'idom-node-id') {
idomDOM.nodeAttributes[nid + '@' + attrib.name] = el.getAttribute(attrib.name);
}
};
// cache the node instance attributes
for (var i = 0; i < el.children[0].attributes.length; i++) {
var attrib = el.children[0].attributes[i];
if (attrib.specified == true) {
idomDOM.instanceAttributes[nid + '@' + attrib.name] = el.children[0].getAttribute(attrib.name);
}
};
el = null;
}
els = null;
idomDOM.cacheDone = true;
};
idom.baseSelector = function(sel) {
function endIndex() {
var nsel = sel.indexOf('@');
return nsel != -1 ? nsel : sel.length
}
return sel.substring(0, endIndex());
};
idom.eventHandler = function(event, el, func) {
var nodeId = el.getAttribute("idom-node-id") ? el.getAttribute("idom-node-id") : getNodeId(el);
if (!nodeId || nodeId.indexOf('@clone@') == -1) {
var err = new Error;
err.message = "idomHandler() may only be invoked on cloned nodes";
throw err.message + '\n' + err.stack;
}
var cidStart = nodeId.indexOf('@clone@');
var forClone = nodeId.substring(cidStart + 7)
var instanceName = el.getAttribute("idom-instance-name") ? el.getAttribute("idom-instance-name") : getInstanceId(el);
if (instanceName) {
func.call(el, event, nodeId, instanceName, forClone);
} else {
func.call(el, event, nodeId, null, forClone);
}
};
// utility functions ...
// commonly needed functions missing from the popular 3rd party libraries
/*
*
* idom.utils.forEachExec(object, property assignment or method invocation)
*
* usage example:
*
* idom.utils.forEachExec(document.querySelectorAll('[idom-id$=someCloneUID]'), 'style.display = "block"')
*
* executes property assignment on all elements in the returned nodelist, or on the returned element
* (if only one)
*
*/
idom.utils.forEachExec = function(obj, str) {
if (arguments.length != 2) {
var e = new Error;
e.message = "params must be: object, method invocation or property assigment"
throw e.message + "\n" + e.stack;
}
var exec = new Function("el", "el." + str);
try {
exec(obj[0] || obj);
} catch (e) {
throw "invalid argument(s): " + e.message + "\n" + e.stack;
}
if (nodelist[0]) {
for (var n = 1; n < obj.length; n++) {
exec(obj[n]);
}
}
};
/*
*
* idom.utils.asyncLoop(length, asyncFunction, callback)
*
* usage example:
*
* idom.utils.asyncLoop(5, someAsyncFunc, someCallback)
*
* someAsyncFunc(loop, iterationCount) {
* doSomeAsyncStuff...
* when done call loop() to continue...
* }
*
* someCallback() {
* this is called after 5 iterations
* }
*
*
*/
idom.utils.asyncLoop = function(length, func, callback){
var i=-1
var loop = function(){
i++;
if (i == length) {
callback();
return;
}
func(loop, i);
}
loop();
}
//useful when assigning spaced or hyphenated strings from JSON/AJAX to idom$() settings such as instanceName
idom.utils.toCamelCase = function() {
return this.replace(/[\-_]/g, " ").replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
if (+match === 0) return "";
// or if (/\s+/.test(match)) for white spaces
return index == 0 ? match.toLowerCase() : match.toUpperCase();
});
};
// useful for finding indexOf a pattern
idom.utils.regexIndexOf = function(str, regex, startpos) {
//force global
regex = new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : ""));
var indxOf = str.substring(startpos || 0).search(regex);
return (indxOf >= 0) ? (indxOf + (startpos || 0)) : indxOf;
}
// useful for finding lastIndexOf a pattern
idom.utils.regexLastIndexOf = function(str, regex, startpos) {
//force global
regex = new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : ""));
if(typeof (startpos) == "undefined") {
startpos = str.length;
} else if (startpos < 0) {
startpos = 0;
}
var stringToWorkWith = this.substring(0, startpos + 1);
var lastIndxOf = -1;
var nextStop = 0;
while((result = regex.exec(stringToWorkWith)) != null) {
lastIndxOf = result.index;
regex.lastIndex = ++nextStop;
}
return lastIndxOf;
}
// internal String method for injecting values into special variable (keys) into the node instance,
// based on key-value JSON data (key-matched variables get their values from JSON values while unmatched
// ones get empty string) -- for internal use
String.prototype._idomMapValues = String.prototype._idomMapValues || function() {
// function used internally so args are assumed to be present
var json = arguments[0];
var uid = arguments[1];
//error check json
var jsonStr, jsonErr;
try {
jsonStr = JSON.stringify(json);
} catch(e) {
jsonErr = true;
}
// primitive, fast error checking ...
if (jsonErr || jsonStr.match(/[\{]{2,}|[\[]/) ) {
var err = new Error;
err.message = 'Invalid data: use simple JSON: {"someKey": "some value", "anotherKey": 5, "yetAnotherKey": true, "andLastButNotLeast": null}'
throw err.message + '\n' + err.stack;
// Notes:
//
// idom works with simple object literal or simple JSON
//
// 'simple JSON' is defined as:
// {"someKey": "some value", "anotherKey": 5, "yetAnotherKey": true, "andLastButNotLeast": null}
// Use Javascript to iterate thru more complex JSON then pass on simple JSON to idom
}
if (jsonStr.match(idom.regex)) {
var err = new Error;
err.message = "Invalid data: idom node variables found in json"
throw err.message + '\n' + err.stack;
}
// RegEx will iterate thru the idom node variables (keys) in target element's virgin innnerHTML (the template),
// match to JSON values (by key), replacing the idom$ vars that match the supplied keys in JSON with the JSON values
// (including null values), and returning the the modified string for updating the target element's innerHTML
return this.replace(idom.regex, function(match) {
var key = match.substr(idom.regexLength);
var val = json[key];
if (typeof eval("json." + key) != 'undefined') {
// the unique for the data cache is a combination of nodeId + instanceName + forClone which assumes
// forClone is globally unique (user enforced for this release), nodeId is unique globally
// (framework enforced) and instanceName is scoped to the node
// Despite that the same node can be linked-in multiple times within a given host node (i.e
// with the same clone id) such duplicate linking must be done after the node is copied
// with a differentiated node id (using idom$cloneBase), so the data cache key will be
// globally unique (although not guaranteed yet due to room for user error in the current release)
idomData.cache[uid.nid + "@" + uid.instanceName + "@" + uid.forClone + '@' + key] = val;
return val;
} else {
// if idom variable is missing or has an empty string value return empty string
return typeof idomData.cache[uid.nid + "@" + uid.instanceName + "@" + uid.forClone + '@' + key] != 'undefined' ?
idomData.cache[uid.nid + "@" + uid.instanceName + "@" + uid.forClone + '@' + key] :
'';
}
});
};
String.prototype._idomMapInstanceAttributes = String.prototype._idomMapInstanceAttributes || function() {
// function used internally so args are assumed to be present
var json = arguments[0];
var uid = arguments[1];
//error check json
var jsonStr, jsonErr;
try {
jsonStr = JSON.stringify(json);
} catch(e) {
jsonErr = true;
}
// primitive, fast error checking ...
if (jsonErr || jsonStr.match(/[\{]{2,}|[\[]/) ) {
var err = new Error;
err.message = 'Invalid data: use simple JSON: {"someKey": "some value", "anotherKey": 5, "yetAnotherKey": true, "andLastButNotLeast": null}'
throw err.message + '\n' + err.stack;
// Notes:
//
// idom works with simple object literal or simple JSON
//
// 'simple JSON' is defined as:
// {"someKey": "some value", "anotherKey": 5, "yetAnotherKey": true, "andLastButNotLeast": null}
// Use Javascript to iterate thru more complex JSON then pass on simple JSON to idom
}
if (jsonStr.match(idom.regex)) {
var err = new Error;
err.message = "Invalid data: idom node variables found in json"
throw err.message + '\n' + err.stack;
}
// RegEx will iterate thru the idom node variables (keys) in target element's virgin innnerHTML (the template),
// match to JSON values (by key), replacing the idom$ vars that match the supplied keys in JSON with the JSON values
// (including null values), and returning the the modified string for updating the target element's innerHTML
return this.replace(idom.regex, function(match) {
var key = match.substr(idom.regexLength);
var val = json[key];
if (typeof eval("json." + key) != 'undefined') {
// the unique for the data cache is a combination of nodeId + targetInstanceName + forClone which assumes
// forClone is globally unique (user enforced for this release), nodeId is unique globally
// (framework enforced) and targetInstanceName is scoped to the node
// Despite that the same node can be linked-in multiple times within a given host node (i.e
// with the same clone id) such duplicate linking must be done after the node is copied
// with a differentiated node id (using idom$cloneBase), so the data cache key will be
// globally unique (although not guaranteed yet due to room for user error in the current release)
idomData.instanceCache[uid.nid + "@" + uid.targetInstanceName + "@" + uid.attribName + '@' + uid.forClone + '@' + key] = val;
return val;
} else {
// if idom variable is missing or has an empty string value return empty string
return typeof idomData.instanceCache[uid.nid + "@" + uid.targetInstanceName + "@" + uid.attribName + '@' + uid.forClone + '@' + key] != 'undefined' ?
idomData.instanceCache[uid.nid + "@" + uid.targetInstanceName + "@" + uid.attribName + '@' + uid.forClone + '@' + key] :
'';
}
});
};
// special version of the general data mapping function (for node-level variables)
String.prototype._idomMapNodeAttributes = String.prototype._idomMapNodeAttributes || function() {
// function used internally so args are assumed to be present
var json = arguments[0];
var uid = arguments[1];
//error check json
var jsonStr, jsonErr;
try {
jsonStr =JSON.stringify(json);
} catch(e) {
jsonErr = true;
}
// primitive, fast error checking ...
if (jsonErr || jsonStr.match(/[\{]{2,}|[\[]/) ) {
var err = new Error;
err.message = 'Invalid data: use simple JSON: {"someKey": "some value", "anotherKey": 5, "yetAnotherKey": true, "andLastButNotLeast": null}'
throw err.message + '\n' + err.stack;
// Notes:
//
// idom works with simple object literal or simple JSON
//
// 'simple JSON' is defined as:
// {"someKey": "some value", "anotherKey": 5, "yetAnotherKey": true, "andLastButNotLeast": null}
// Use Javascript to iterate thru more complex JSON then pass on simple JSON to idom
} else if (jsonStr.match(idom.regex)) {
var err = new Error;
err.message = "Invalid data: idom node variables found in json"
throw err.message + '\n' + err.stack;
}
// In the case of the element's inline style, class attributes and inline event handlers RegEx will iterate
// thru the idom node variables (keys) in target element's virgin style or class attribute values or in the
// inline event handlers values (the template), match to JSON values (by key), replacing the idom$ vars that
// match the supplied keys in JSON with the JSON values (including null values), and returning the the modified
// string for updating the target element's style or class attribute values
return this.replace(idom.regex, function(match) {
var key = match.substr(idom.regexLength);
var val = json[key];
if (typeof eval("json." + key) != 'undefined') {
// the unique for the data cache for node-level idom$ vars is a combination of nodeId + forClone
// which assumes forClone is globally unique (user enforced for this release) and nodeId is globally
// unique too (framework enforced)
// Despite that the same node can be linked-in multiple times within a given host node (i.e
// with the same clone id) such duplicate linking must be done after the node is copied
// with a differentiated node id (using idom$cloneBase), so the node-level data cache key will
// be globally unique (although not guaranteed yet due to room for user error in the current release)
idomData.nodeCache[uid.nid + "@" + uid.attribName + '@' + uid.forClone + '@' + key] = val;
return val;
} else {
// if idom variable is missing or has an empty string value return empty string
return typeof idomData.nodeCache[uid.nid + "@" + uid.attribName + '@' + uid.forClone + '@' + key] != 'undefined' ?
idomData.nodeCache[uid.nid + "@" + uid.attribName + '@' + uid.forClone + '@' + key] :
'';
}
});
};
// Main method
Element.prototype.idom$ = Element.prototype.idom$ || function() {
if (!idomDOM.cacheDone) {
var err = new Error;
err.message = "you must run idom.cache() before invoking idom$ methods";
throw err.message + '\n' + err.stack;
}
var fullNid = this.getAttribute('idom-node-id');
var nid = fullNid.replace(new RegExp("([@])(.)+$", "g"), "");
if (!idomDOM.cache[nid]) {
// node was added after idom.cache()
var err = new Error;
err.message = "the node prototype for this node was not cached";
throw err.message + '\n' + err.stack;
}
if (!idomDOM.nodeShell[nid]) {
// node was added after idom.cache()
var err = new Error;
err.message = "the node was not cached";
throw err.message + '\n' + err.stack;
}
// isPopulated() checks if node structure has been corrupted by user or 3rd party library and throws an error
// return value is used elsewhere in this function
var isPopulated = this.idom$isPopulated();
if ((!arguments[0] || typeof arguments[0] != 'object') || (!arguments[1] || typeof arguments[1] != 'object') || arguments.length != 2){
var err = new Error;
err.message = "idom$ expects two arguments as Simple JSON objects: data, settings";
throw err.message + '\n' + err.stack;
} else {
var json = arguments[0];
var settings = arguments[1];
}
// json is error checked in string replace function
// error check settings
if (settings != {}) {
var optErr, settingsStr;
try {
settingsStr = JSON.stringify(settings);
} catch (e) {
optErr = true;
}
// primitive, fast error checking ...
if (optErr || settingsStr.match(/[\{]{2,}|[\[]/)) {
var err = new Error;
err.message = 'Invalid settings: use simple JSON. {"someKey": "some value", "anotherKey": 5, "yetAnotherKey": true, "andLastButNotLeast": null}';
throw err.message + '\n' + err.stack;
// Notes:
//
// idom works with simple JSON
//
// 'simple JSON' is defined as a key-value collection, limited to string or numeric values
// Like {"someKey": "some value", "anotherKey": 5, "yetAnotherKey": true, "andLastButNotLeast": null}
}
if (settingsStr.match(idom.regex)) {
var err = new Error;
err.message = "Invalid settings: idom node variables found in settings";
throw err.message + '\n' + err.stack;
}
if (settingsStr.indexOf('@') != -1) {
var err = new Error;
err.message = "values in settings must not include @ references (they're inferred at run time) \n" +
"use idom.baseSelector(long@format@value) to pass the base values"
throw err.message + '\n' + err.stack;
}
};
if (fullNid.indexOf('@clone@') == -1) {
if (!settings && !settings.forClone) {
var err = new Error;
err.message = "Missing setting: you must specify forClone (during instance creation)";
throw err.message + '\n' + err.stack;
}
var forClone = settings.forClone;
var isCloned = false;
} else {
if (settings.forClone) {