-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpenjs.js
2537 lines (2537 loc) · 79 KB
/
penjs.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
(function (exportName) {
/**
* @file penjs
* @url git+https://github.com/zswang/penjs.git
* Mobile-web small development framework.
* @author
* zswang (http://weibo.com/zswang)
* @version 0.1.11
* @date 2017-05-04
* @license MIT
*/
/*<function name="parser_void_elements">*/
var parser_void_elements = [
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen',
'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr'
]; /*</function>*/
/*<function name="parser_tokenizer" depend="parser_void_elements">*/
var parser_guid = 0;
function parser_tokenizer(code) {
var resultNodes = [];
/**
* 当前扫描起始位置
*/
var scanpos = 0;
function pushToken(type, pos, endpos) {
if (endpos <= pos) {
return;
}
var node = {
id: (parser_guid++).toString(36),
type: type,
pos: pos,
endpos: endpos,
};
if (type === 'text' || type === 'comment') {
node.value = code.slice(pos, endpos);
}
scanpos = endpos;
resultNodes.push(node);
return node;
}
while (scanpos < code.length) {
var match = code.slice(scanpos).match(/([^\S\n]*)(?:<(!--)|<\/(:?[\w_]+[\w_-]*[\w_]|[\w_]+)\s*>|<(:?[\w_]+[\w_-]*[\w_]|[\w_]+)\s*)/);
if (!match) {
break;
}
pushToken('text', scanpos, scanpos + match.index); // 记录 text
var offset = match[0].length;
var indent = match[1];
if (match[2]) {
match = code.slice(scanpos + offset).match(/-->/);
if (!match) {
var node_1 = pushToken('comment', scanpos, code.length);
node_1.indent = indent;
break;
}
offset += match.index + match[0].length;
var node_2 = pushToken('comment', scanpos, scanpos + offset);
node_2.indent = indent;
continue;
}
var tag = match[3];
if (tag) {
var node_3 = pushToken('right', scanpos, scanpos + offset);
node_3.tag = tag;
node_3.indent = indent;
continue;
}
// "<tag"
tag = match[4];
var attrs = [];
// find attrs
while (true) {
// find attrName
match = code.slice(scanpos + offset).match(/^\s*([:@]?[\w_]+[\w_\-.]*[\w_]|[\w_]+)\s*/);
if (!match) {
break;
}
offset += match[0].length;
var attrName = match[1];
var attrValue = '';
var quoted = '';
// find attrValue
match = code.slice(scanpos + offset).match(/^\s*=\s*((')([^']*)'|(")([^"]*)"|([^'"\s\/>]+))\s*/);
if (match) {
offset += match[0].length;
attrValue = match[1];
quoted = match[2] || match[4] || '';
}
switch (quoted) {
case '"':
case "'":
attrValue = attrValue.slice(1, -1);
break;
}
attrs.push({
name: attrName,
value: attrValue,
quoted: quoted,
});
}
match = code.slice(scanpos + offset).match(/^\s*(\/?)>/);
if (!match) {
break;
}
offset += match[0].length;
var single = match[1] || parser_void_elements.indexOf(tag) >= 0;
var node = pushToken(single ? 'single' : 'left', scanpos, scanpos + offset);
node.tag = tag;
node.attrs = attrs;
node.indent = indent;
node.selfClosing = parser_void_elements.indexOf(tag) >= 0;
}
pushToken('text', scanpos, code.length); // 记录 text
return resultNodes;
} /*</function>*/
/*<function name="parser_parse" depend="parser_tokenizer">*/
/**
* 解析 HTML 代码
*
* @param code
* @return 返回根节点
* @example parser_parse:base
```js
var node = jnodes.Parser.parse(`<!-- ts --><div class="box"></div>`);
console.log(JSON.stringify(node).replace(/"id":"\w+",/g, ''));
// > {"type":"root","pos":0,"endpos":34,"children":[{"type":"comment","pos":0,"endpos":11,"value":"<!-- ts -->","indent":""},{"type":"block","pos":11,"endpos":34,"tag":"div","attrs":[{"name":"class","value":"box","quoted":"\""}],"indent":"","selfClosing":false,"children":[]}]}
```
* @example parser_parse:text
```js
var node = jnodes.Parser.parse(`hello`);
console.log(JSON.stringify(node).replace(/"id":"\w+",/g, ''));
// > {"type":"root","pos":0,"endpos":5,"children":[{"type":"text","pos":0,"endpos":5,"value":"hello"}]}
```
* @example parser_parse:comment not closed.
```js
var node = jnodes.Parser.parse(`<!-- okay`);
console.log(JSON.stringify(node).replace(/"id":"\w+",/g, ''));
// > {"type":"root","pos":0,"endpos":9,"children":[{"type":"comment","pos":0,"endpos":9,"value":"<!-- okay","indent":""}]}
```
* @example parser_parse:attribute is emtpy
```js
var node = jnodes.Parser.parse(`<div><input type=text readonly></div>`);
console.log(JSON.stringify(node).replace(/"id":"\w+",/g, ''));
// > {"type":"root","pos":0,"endpos":37,"children":[{"type":"block","pos":0,"endpos":37,"tag":"div","attrs":[],"indent":"","selfClosing":false,"children":[{"type":"single","pos":5,"endpos":31,"tag":"input","attrs":[{"name":"type","value":"text","quoted":""},{"name":"readonly","value":"","quoted":""}],"indent":"","selfClosing":true}]}]}
```
* @example parser_parse:tag not closed
```js
var node = jnodes.Parser.parse(`<input type=text readonly`);
console.log(JSON.stringify(node).replace(/"id":"\w+",/g, ''));
// > {"type":"root","pos":0,"endpos":25,"children":[{"type":"text","pos":0,"endpos":25,"value":"<input type=text readonly"}]}
```
* @example parser_parse:tag asymmetric
```js
var node = jnodes.Parser.parse(`<div><span></div></span>`);
console.log(JSON.stringify(node).replace(/"id":"\w+",/g, ''));
// * throw
```
* @example parser_parse:tag asymmetric
```js
var node = jnodes.Parser.parse(`<section><div></div>\n</span>`);
console.log(JSON.stringify(node).replace(/"id":"\w+",/g, ''));
// * throw
```
* @example parser_parse:tag nesting
```js
var node = jnodes.Parser.parse(`<div><div><div></div><div></div></div></div>`);
console.log(JSON.stringify(node).replace(/"id":"\w+",/g, ''));
// > {"type":"root","pos":0,"endpos":44,"children":[{"type":"block","pos":0,"endpos":44,"tag":"div","attrs":[],"indent":"","selfClosing":false,"children":[{"type":"block","pos":5,"endpos":38,"tag":"div","attrs":[],"indent":"","selfClosing":false,"children":[{"type":"block","pos":10,"endpos":21,"tag":"div","attrs":[],"indent":"","selfClosing":false,"children":[]},{"type":"block","pos":21,"endpos":32,"tag":"div","attrs":[],"indent":"","selfClosing":false,"children":[]}]}]}]}
```
* @example parser_parse:attribute spance
```js
var node = jnodes.Parser.parse(`<input type="text" placeholder="What needs to be done?"/>`);
console.log(JSON.stringify(node).replace(/"id":"\w+",/g, ''));
// > {"type":"root","pos":0,"endpos":57,"children":[{"type":"single","pos":0,"endpos":57,"tag":"input","attrs":[{"name":"type","value":"text","quoted":"\""},{"name":"placeholder","value":"What needs to be done?","quoted":"\""}],"indent":"","selfClosing":true}]}
```
*/
function parser_parse(code) {
var root = {
id: (parser_guid++).toString(36),
type: 'root',
pos: 0,
endpos: code.length,
children: [],
};
var current = root;
var tokens = parser_tokenizer(code);
var lefts = []; // 左边标签集合,用于寻找配对的右边标签
tokens.forEach(function (token) {
switch (token.type) {
case 'comment':
case 'single':
case 'text':
current.children.push(token);
current.endpos = token.endpos;
break;
case 'left':
token.children = [];
lefts.push(token);
current.children.push(token);
current = token;
break;
case 'right':
var buffer = void 0;
var line = void 0;
var col = void 0;
var error = void 0;
if (lefts.length <= 0) {
buffer = code.slice(0, token.endpos).split('\n');
line = buffer.length;
col = buffer[buffer.length - 1].length + 1;
error = 'No start tag. (line:' + token.line + ' col:' + token.col + ')';
console.error(error);
throw error;
}
for (var i = lefts.length - 1; i >= 0; i--) {
var curr = lefts[i];
var prev = lefts[i - 1];
if (curr.tag === token.tag) {
curr.type = 'block';
curr.endpos = token.endpos;
if (prev) {
current = prev;
}
else {
current = root;
}
current.endpos = curr.endpos;
lefts = lefts.slice(0, i);
break;
}
else {
if (!prev) {
buffer = code.slice(0, token.endpos).split('\n');
line = buffer.length;
col = buffer[buffer.length - 1].length + 1;
error = 'No start tag. (line:' + token.line + ' col:' + token.col + ')';
console.error(error);
throw error;
}
curr.type = 'text';
delete curr.children; // 移除子节点
delete curr.tag;
delete curr.attrs;
}
}
break;
}
});
return root;
}
/*</function>*/
/*<function name="parser_build">*/
/**
* @preview
```html
<!-- beforebegin -->
<p>
<!-- afterbegin -->
foo
<!-- beforeend -->
</p>
<!-- afterend -->
```
* @param node
* @param hook
* @return 返回构建后的 HTML 字符串
* @example parser_build:base
```js
var node = jnodes.Parser.parse(`<input type=text readonly>`)
console.log(jnodes.Parser.build(node));
// > <input type=text readonly>
console.log(JSON.stringify(jnodes.Parser.build()));
// > ""
```
* @example parser_build:hook
```js
var node = jnodes.Parser.parse(`<div>text</div>`)
console.log(jnodes.Parser.build(node, null, function (node, options) {
if (node.tag) {
node.beforebegin = `[beforebegin]`;
node.beforeend = `[beforeend]`;
node.afterbegin = `[afterbegin]`;
node.afterend = `[afterend]`;
}
}));
// > [beforebegin]<div>[beforeend]text[afterbegin]</div>[afterend]
```
* @example parser_build:hook overwriteNode
```js
var node = jnodes.Parser.parse(`<div><tnt/></div>`)
console.log(jnodes.Parser.build(node, null, function (node, options) {
if (node.tag === 'tnt') {
node.overwriteNode = `<img src="tnt.png">`;
}
}));
// > <div><img src="tnt.png"></div>
```
* @example parser_build:hook overwriteAttrs
```js
var node = jnodes.Parser.parse(`<div><bigimg alt="none"/></div>`)
console.log(jnodes.Parser.build(node, null, function (node, options) {
if (node.tag === 'bigimg') {
node.overwriteAttrs = `src="tnt.png" alt="tnt"`;
}
}));
// > <div><bigimg src="tnt.png" alt="tnt"/></div>
var node = jnodes.Parser.parse(`<div><bigimg alt="none"/></div>`)
console.log(jnodes.Parser.build(node, null, function (node, options) {
if (node.tag === 'bigimg') {
node.overwriteAttrs = ``;
}
}));
// > <div><bigimg/></div>
```
* @example parser_build:indent
```js
var node = jnodes.Parser.parse(`<div>\n <span>hello</span>\n</div>`)
console.log(JSON.stringify(jnodes.Parser.build(node)));
// > "<div>\n <span>hello</span>\n</div>"
```
*/
function parser_build(node, options, hook) {
if (!node) {
return '';
}
var indent = node.indent || '';
if (hook) {
hook(node, options);
}
if (node.overwriteNode) {
return node.overwriteNode;
}
var result = '';
if (node.beforebegin) {
result += node.beforebegin;
}
if (node.type === 'text' || node.type === 'comment') {
result += node.value;
}
else if (node.tag) {
if (!result || result[result.length - 1] === '\n') {
result += indent;
}
result += '<' + node.tag;
if (typeof node.overwriteAttrs === 'string') {
if (node.overwriteAttrs) {
result += ' ' + node.overwriteAttrs;
}
}
else {
node.attrs.forEach(function (attr) {
result += ' ' + attr.name;
if (attr.value) {
result += '=' + attr.quoted + attr.value + attr.quoted;
}
});
}
if (node.type === 'single') {
if (!node.selfClosing) {
result += '/';
}
result += '>';
}
else {
result += '>';
}
}
if (!node.selfClosing && node.type !== 'single') {
if (node.beforeend) {
result += node.beforeend;
}
if (node.children) {
node.children.forEach(function (item) {
item.parent = node;
result += parser_build(item, options, hook);
});
}
if (node.afterbegin) {
result += node.afterbegin;
}
if (node.tag) {
if (result[result.length - 1] === '\n') {
result += indent;
}
result += '</' + node.tag + '>';
}
}
if (node.afterend) {
result += node.afterend;
}
return result;
} /*</function>*/
/*<function name="observer">*/
/**
* 监听数据改版
*
* @param model 数据
* @param trigger 触发函数
* @example observer():trigger is undefined
```js
var data = { a: 1 };
jnodes.observer(data);
```
* @example observer():trigger
```js
var data = { a: 1 };
jnodes.observer(data, function () {
console.log(data.a);
});
data.a = 2;
// > 2
```
* @example observer():filter
```js
var data = { a: 1, b: 1 };
var count = 0;
jnodes.observer(data, function () {
count++;
}, function (key) {
return key === 'a';
});
data.a = 2;
console.log(count);
// > 1
data.a = 2;
console.log(count);
// > 1
data.b = 2;
console.log(count);
// > 1
```
* @example observer():configurable is false
```js
var data = { a: 1 };
Object.defineProperty(data, 'a', {
enumerable: true,
configurable: false,
});
var i = 0;
jnodes.observer(data, function () {
i = 1;
});
data.a = 2;
console.log(i);
// > 0
```
* @example observer():getter/setter
```js
var data = { a: 1 };
var _x = 0;
Object.defineProperty(data, 'x', {
enumerable: true,
configurable: true,
get: function () {
return _x;
},
set: function (value) {
_x = value;
}
});
jnodes.observer(data, function () {});
data.x = 123;
console.log(data.x);
// > 123
```
* @example observer():array
```js
var data = [1, 2, 3];
var count = 0;
jnodes.observer(data, function () {
count++;
});
data.push(4);
console.log(count);
// > 1
data.sort();
console.log(count);
// > 2
```
*/
function observer(model, trigger, filter) {
if (!trigger) {
return;
}
function define(key, value) {
// 过滤处理
if (filter && !filter(key)) {
return;
}
var property = Object.getOwnPropertyDescriptor(model, key);
if (property && property.configurable === false) {
return;
}
// cater for pre-defined getter/setters
var getter = property && property.get;
var setter = property && property.set;
Object.defineProperty(model, key, {
enumerable: true,
configurable: true,
get: function () {
return getter ? getter.call(model) : value;
},
set: function (newVal) {
var val = getter ? getter.call(model) : value;
if (newVal === val) {
return;
}
if (setter) {
setter.call(model, newVal);
}
else {
value = newVal;
}
trigger(model);
}
});
}
if (Array.isArray(model)) {
[
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse',
]
.forEach(function (method) {
// cache original method
var original = model[method];
Object.defineProperty(model, method, {
value: function () {
var result = original.apply(this, arguments);
trigger(model);
return result;
},
enumerable: false,
writable: true,
configurable: true,
});
});
}
else {
Object.keys(model).forEach(function (key) {
define(key, model[key]);
});
}
} /*</function>*/
/*<function name="Parser" depend="parser_parse,parser_build">*/
var Parser = {
parse: parser_parse,
build: parser_build,
}; /*</function>*/
/*<function name="Binder" depend="observer">*/
var jnodes_guid = 0;
/**
* @example bind():base
```js
jnodes.binder = new jnodes.Binder();
var data = {x: 1, y: 2};
var rootScope = {};
var count = 0;
jnodes.binder.bind(data, rootScope, function (output) {
output.push('<div></div>');
count++;
});
console.log(rootScope.children.length);
// > 1
var element = {};
global.document = { querySelector: function(selector) {
console.log(selector);
// > [data-jnodes-scope="0"]
return element;
} };
console.log(count);
// > 0
data.x = 2;
console.log(count);
// > 1
console.log(JSON.stringify(element));
// > {"outerHTML":"<div></div>"}
console.log(JSON.stringify(jnodes.binder.scope('none')));
// > undefined
console.log(JSON.stringify(jnodes.binder.templateAdapter('none')));
// > undefined
console.log(JSON.stringify(jnodes.binder.templateRender('none')));
// > undefined
console.log(JSON.stringify(jnodes.binder._attrsRender(rootScope)));
// > ""
var scope = {
children: [{
model: {
$$binds: function () {
return [];
}
}
}]
};
jnodes.binder.cleanChildren(scope);
var scope = {
children: [{
model: {}
}]
};
jnodes.binder.cleanChildren(scope);
jnodes.binder.update();
var scope = {
type: 'depend',
binder: jnodes.binder,
parent: {
type: 'bind',
binder: jnodes.binder,
model: {}
}
};
var data = { x: 1 };
jnodes.binder.observer(data, scope);
data.x = 2;
var scope = {
type: 'depend',
binder: jnodes.binder,
parent: {
type: 'depend',
binder: jnodes.binder,
model: {
$$binds: function () {
return [{
id: 0,
type: 'bind',
binder: jnodes.binder,
model: {},
}, {
id: 0,
type: 'depend',
binder: jnodes.binder,
model: {},
parent: {
binder: jnodes.binder,
model: {},
}
}]
},
},
},
};
var data = { x: 1 };
jnodes.binder.observer(data, scope);
data.x = 2;
var $$scope = {
id: 0,
type: 'bind',
binder: jnodes.binder,
model: {},
};
var $$binds = function() {
return [$$scope]
};
var parent = {
id: 0,
type: 'depend',
binder: jnodes.binder,
model: {},
parent: {
id: 0,
type: 'bind',
binder: jnodes.binder,
model: {
$$binds: $$binds
},
}
};
var scope = {
type: 'depend',
binder: jnodes.binder,
parent: {
type: 'depend',
binder: jnodes.binder,
model: {
$$binds: function () {
return [{
id: 0,
type: 'bind',
binder: jnodes.binder,
model: {},
}, parent, parent]
}
},
},
};
var data = { x: 1 };
jnodes.binder.observer(data, scope);
data.x = 2;
```
* @example bind():bind jhtmls
```html
<div>
<script type="text/jhtmls">
<h1 :class="{book: Math.random() > 0.5}">Books</h1>
<ul :bind="books" @create="books.loaded = 'done'">
books.forEach(function (book) {
<li :bind="book">
<:template name="book"/>
</li>
});
</ul>
</script>
</div>
<script type="text/jhtmls" id="book">
<a href="#{id}">#{title}</a>
</script>
```
```js
jnodes.binder = new jnodes.Binder();
var books = [{id: 1, title: 'book1'}, {id: 2, title: 'book2'}, {id: 3, title: 'book3'}];
jnodes.binder.registerAdapter('jhtmls', function (templateCode, bindObjectName) {
var node = jnodes.Parser.parse(templateCode);
var code = jnodes.Parser.build(node, bindObjectName, adapter_jhtmls);
return jhtmls.render(code);
});
var bookRender = jnodes.binder.templateAdapter('jhtmls', document.querySelector('#book').innerHTML);
jnodes.binder.registerTemplate('book', function (scope) {
return bookRender(scope.model);
});
var div = document.querySelector('div');
div.innerHTML = jnodes.binder.templateAdapter('jhtmls', div.querySelector('script').innerHTML)({
books: books
});
var rootScope = jnodes.binder.$$scope;
rootScope.element = null;
rootScope.element = div;
console.log(rootScope.element === div);
// > true
console.log(div.querySelector('ul li a').innerHTML);
// > book1
books[0].title = 'Star Wars';
console.log(div.querySelector('ul li a').innerHTML);
// > Star Wars
books[0].title = 'Jane Eyre';
console.log(div.querySelector('ul li a').innerHTML);
// > Jane Eyre
console.log(jnodes.binder.scope(div) === rootScope);
// > true
console.log(jnodes.binder.scope(div.querySelector('ul li a')).model.id === 1);
// > true
books.shift();
console.log(jnodes.binder.scope(div.querySelector('ul li a')).model.id === 2);
// > true
```
* @example bind():bind jhtmls 2
```html
<div>
<script type="text/jhtmls">
<ul :bind="books" :data-length="books.length" @create="books.loaded = 'done'" class="books">
books.forEach(function (book) {
<li :bind="book" @click="book.star = !book.star" class="" :class="{star: book.star}">
<a :href="'/' + book.id" :bind="book.title" @destroy="console.info('destroy')">#{book.title}</a>
<span :bind="book.id" :data-star="book.star">#{book.id}</span>
</li>
});
</ul>
</script>
</div>
```
```js
jnodes.binder = new jnodes.Binder({});
var books = [{id: 1, title: 'book1', star: false}, {id: 2, title: 'book2', star: false}, {id: 3, title: 'book3', star: false}];
jnodes.binder.registerAdapter('jhtmls', function (templateCode, bindObjectName) {
var node = jnodes.Parser.parse(templateCode);
var code = jnodes.Parser.build(node, bindObjectName, adapter_jhtmls);
return jhtmls.render(code);
});
var div = document.querySelector('div');
div.innerHTML = jnodes.binder.templateAdapter('jhtmls', div.querySelector('script').innerHTML)({
books: books
});
var rootScope = jnodes.binder.$$scope;
rootScope.element = div;
console.log(books.loaded);
// > done
console.log(JSON.stringify(jnodes.binder.scope(div.querySelector('ul li a')).model));
// > "book1"
console.log(JSON.stringify(jnodes.binder.scope(div.querySelector('ul li span')).model));
// > 1
books.shift();
console.log(JSON.stringify(jnodes.binder.scope(div.querySelector('ul li a')).model));
// > "book2"
function findEventTarget(parent, target, selector) {
var elements = [].slice.call(parent.querySelectorAll(selector));
while (target && elements.indexOf(target) < 0) {
target = target.parentNode;
}
return target;
}
['click'].forEach(function (eventName) {
document.addEventListener(eventName, function (e) {
if (e.target.getAttribute('data-jnodes-event-input')) {
if (eventName === 'focusin') {
e.target.addEventListener('input', triggerScopeEvent)
} else if (eventName === 'focusout') {
e.target.removeEventListener('input', triggerScopeEvent)
}
}
var target = findEventTarget(document, e.target, '[data-jnodes-event-' + eventName + ']');
if (!target) {
return;
}
jnodes.binder.triggerScopeEvent(e, target);
})
});
var li = div.querySelector('ul li');
li.click();
var li = div.querySelector('ul li');
console.log(li.className);
// > star
```
* @example bind():update
```js
var data = {x: 1, y: 2};
var binder = new jnodes.Binder();
var scope = binder.bind(data, null, null);
var element = {};
global.document = { querySelector: function(selector) {
return element;
} };
binder.update(scope);
console.log(JSON.stringify(element));
// > {}
var scope = binder.bind(data, null, null, function (output) {
output.push('<div></div>');
});
var element = {};
global.document = { querySelector: function(selector) {
return element;
} };
binder.update(scope);
console.log(JSON.stringify(element));
// > {"innerHTML":"<div></div>"}
```
* @example bind():attr is null
```html
<div>
<script type="text/jhtmls">
<input type="checkbox" :checked="checked">
</script>
</div>
```
```js
var binder = new jnodes.Binder();
var data = { checked: false };
var div = document.querySelector('div');
jnodes.binder.registerAdapter('jhtmls', function (templateCode, bindObjectName) {
var node = jnodes.Parser.parse(templateCode);
var code = jnodes.Parser.build(node, bindObjectName, adapter_jhtmls);
return jhtmls.render(code);
});
div.innerHTML = jnodes.binder.templateAdapter('jhtmls', div.querySelector('script').innerHTML)(data);
var rootScope = jnodes.binder.$$scope;
rootScope.element = div;
console.log(div.innerHTML.trim());
// > <input type="checkbox">
data.checked = true;
console.log(div.innerHTML.trim());
// > <input checked="" type="checkbox">
```
*/
var Binder = (function () {
function Binder(options) {
var _this = this;
this._adapters = {};
options = options || {};
this._binds = {};
this._templates = {};
this._adapters = {};
this._bindObjectName = options.bindObjectName || 'jnodes.binder';
this._bindAttributeName = options.bindAttributeName || 'bind';
this._dependAttributeName = options.dependAttributeName || 'depend';
this._scopeAttributeName = options.scopeAttributeName || "data-jnodes-scope";
this._eventAttributePrefix = options.eventAttributePrefix || "data-jnodes-event-";
this._imports = options.imports;
this._templates = {};
this._checkers = {};
this._findElement = options.findElement || (function (scope) {
return document.querySelector("[" + _this._scopeAttributeName + "=\"" + scope.id + "\"]");
});
this._updateElement = options.updateElement || (function (element, scope) {
if (!element || (!scope.outerRender && !scope.innerRender)) {
return;
}
_this.lifecycleEvent(scope, 'destroy');
_this.cleanChildren(scope);
var output = [];
if (!scope.innerRender) {
scope.outerRender(output, true);
element.outerHTML = output.join('');
}
else if (!scope.outerRender) {
scope.innerRender(output);
element.innerHTML = output.join('');
}
else {
scope.outerRender(output, false);
var shell = output.join('');
output = [];
if (scope.shell === shell) {
scope.innerRender(output);
element.innerHTML = output.join('');
}
else {
scope.shell = shell;
scope.outerRender(output, true);
element.outerHTML = output.join('');
}
}
_this.lifecycleEvent(scope, 'create');
_this.lifecycleEvent(scope, 'update');
});
this._attrsRender = options.attrsRender || (function (scope, attrs, node) {
if (!attrs) {
return '';
}
var dictValues = {};
var dictQuoteds = {};
var hasScopeAttr = false;
attrs.filter(function (attr) {
if (':' !== attr.name[0] && '@' !== attr.name[0]) {
return true;
}
var name = attr.name.slice(1);
if (name !== _this._bindAttributeName && name !== _this._dependAttributeName) {
return true;
}
name = _this._scopeAttributeName;
dictQuoteds[name] = attr.quoted;
dictValues[name] = [scope.id];
hasScopeAttr = true;
scope.methods = scope.methods || {};
Object.keys(scope.methods).forEach(function (key) {
if (typeof scope.methods[key] === 'function') {
if (!scope.methods[key].$$scope) {
delete scope.methods[key];
}
}
});
}).filter(function (attr) {
if (':' !== attr.name[0] && '@' !== attr.name[0]) {
return true;
}
var name = attr.name.slice(1);
if ('@' === attr.name[0]) {
var arr = name.split('.');
name = arr[0];
if (name === 'create') {
scope.lifecycleCreate = true;
}
else if (name === 'destroy') {
scope.lifecycleDestroy = true;
}
else if (name === 'update') {
scope.lifecycleUpdate = true;
}
name = _this._eventAttributePrefix + name;
}
var values = dictValues[name] = dictValues[name] || [];
dictQuoteds[name] = attr.quoted;
if (attr.value === '' || attr.value === null || attr.value === undefined ||
attr.value === false) {
return;
}
switch (typeof attr.value) {
case 'boolean':
case 'number':
case 'string':
values.push(attr.value);
break;
case 'object':
Object.keys(attr.value).forEach(function (key) {
if (attr.value[key]) {
values.push(key);
}
});
break;
case 'function':
scope.methods = scope.methods || {};
var methodId = void 0;
if (hasScopeAttr) {
methodId = scope.methods["v:" + attr.value];
}
if (!methodId) {
methodId = "@" + (jnodes_guid++).toString(36);
scope.methods[methodId] = attr.value;
if (hasScopeAttr) {
attr.value.$$scope = scope;
scope.methods["v:" + attr.value] = methodId;
}
}
values.push(methodId);
break;
}
}).forEach(function (attr) {