-
Notifications
You must be signed in to change notification settings - Fork 3
/
jtmpl.coffee.html
712 lines (616 loc) · 25.8 KB
/
jtmpl.coffee.html
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
863
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
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="css/styles.css">
<link rel="stylesheet" href="css/highlight.css">
<title>jtmpl</title>
</head>
<body>
<div class="wrapper">
<h1 id="-span-span-rsaquo-span-span-jtmpl-sup-0-2-0-sup-"><span>{<span>›</span></span> <a href="/">jtmpl</a> <sup>0.2.0</sup></h1>
<h2 id="interface">Interface</h2>
<h3 id="compile-">Compile:</h3>
<p>String jtmpl(String template, AnyType model)</p>
<h3 id="compile-and-bind-browser-only-">Compile and bind (browser only):</h3>
<p>void jtmpl(DOMElement target, String template, AnyType model)</p>
<p><code>target</code> and <code>template</code> can be Strings in the format "#element-id".</p>
<h3 id="main-function">Main function</h3>
<p>Target NodeJS and browser</p>
<pre><code>jtmpl = (exports ? this).jtmpl = (target, template, model, options) ->
# Deprecated. `jtmpl(selector)`?
if (target is null or typeof target is 'string') and not template?
if not document?
throw new Error(':( this API is only available in a browser')
return apslice.call(document.querySelectorAll(target))
# `jtmpl(template, model)`?
if typeof target is 'string' and
typeof template in ['number', 'string', 'boolean', 'object'] and
(model is undefined or model is null)
model = template
template = target
target = undefined
# `jtmpl('#element-id', ...)`?
if typeof target is 'string' and target.match(RE_NODE_ID)
target = document.getElementById(target.substring(1))
if not model?
throw new Error(':( no model')
# `jtmpl('#template-id', ...)` or `jtmpl(element, '#template-id', ...)`
if template.match and template.match(RE_NODE_ID)
template = document.getElementById(template.substring(1)).innerHTML
# options
options = options or {}
# string-separated opening and closing delimiter
options.delimiters = (options.delimiters or '{{ }}').split(' ')
# delimiters are changed in the generated HTML comment-enclosed section prototype
# to avoid double-parsing
options.compiledDelimiters = (options.compiledDelimiters or '<<< >>>').split(' ')
# sections not enclosed in HTML tag are automatically enclosed
options.defaultSection = options.defaultSectionTag or 'div'
# default for section items
options.defaultSectionItem = options.defaultSectionItem or 'div'
# default for section items
options.defaultVar = options.defaultVar or 'span'
# default target tag
options.defaultTargetTag = options.defaultTargetTag or 'div'
delimiters = options.delimiters
## Preprocess template
template = ('' template)
# Convert triple mustache (output unescaped var) to alt form
.replace(regexp("{{{ (#{ RE_IDENTIFIER }) }}}"), delimiters[0] '&$1' delimiters[1])
# Strip HTML comments that enclose tokens
.replace(regexp("<!-- #{ RE_SPACE } ({{ #{ RE_ANYTHING } }}) #{ RE_SPACE } -->", delimiters), '$1')
# Strip single quotes around html element attributes associated with tokens
.replace(regexp("(#{ RE_IDENTIFIER })='({{ #{ RE_IDENTIFIER } }})'", delimiters), '$1=$2')
# Strip double quotes around html element attributes associated with tags
.replace(regexp("(#{ RE_IDENTIFIER })=\"({{ #{ RE_IDENTIFIER } }})\"", delimiters), '$1=$2')
# If tags stand on their own line remove the line, keep the tag only
.replace(regexp("\\n #{ RE_SPACE } ({{ #{ RE_ANYTHING } }}) #{ RE_SPACE } \\n", delimiters), '\n$1\n')
# Compile template
html = jtmpl.compile(template, model, null, false, options)
# Done?
if not target then return html
if target.nodeName is 'SCRIPT'
newTarget = document.createElement(options.defaultTargetTag)
target.parentNode.replaceChild(newTarget, target)
target = newTarget
# Construct DOM
target.innerHTML = html
# Bind recursively using data-jt attributes
jtmpl.bind(target, model)</code></pre>
<h2 id="rules">Rules</h2>
<p>jtmpl is a processor of rules. </p>
<p>Rules in sequences are in increasing generality order. It's just like
<a href="http://learnyouahaskell.com/syntax-in-functions">Haskell pattern matching</a>.</p>
<p>Compilation and binding stages can be extended with new rules,
put them at the beginning:</p>
<p><code>jtmpl.compileRules.unshift({ new compile rule... })</code><br><code>jtmpl.bindRules.unshift({ new binding rule... })</code></p>
<h3 id="regular-expression-atoms">Regular expression atoms</h3>
<p>Used in various matchers</p>
<pre><code>RE_IDENTIFIER = '[\\w\\.\\-] '
RE_NODE_ID = '^#[\\w\\.\\-] $'
RE_ANYTHING = '[\\s\\S]*?'
RE_SPACE = '\\s*'
RE_DATA_JT = '(?: ( \\s* data-jt = " [^"]* )" )?'</code></pre>
<h3 id="pre-processing-rules">Pre-processing rules</h3>
<p>Transformations to clean up template for easier matching</p>
<pre><code>jtmpl.preprocessingRules = [
{ pattern: "", replaceWith: "" }
{ pattern: "", replaceWith: "" }
{ pattern: "", replaceWith: "" }
]</code></pre>
<h3 id="compile-rules">Compile rules</h3>
<p>Delimiters in <code>pattern</code>s are replaced with escaped options.delimiters, whitespace - stripped.</p>
<p>Inline tags implement <code>replaceWith</code>, section (block) tags implement <code>contents</code>.</p>
<p>Signatures:</p>
<p>[String, Array] <code>replaceWith</code> (String for each group in pattern, AnyType model)</p>
<p>String <code>bindingToken</code> (String for each group in pattern)</p>
<p>[String, Array] <code>contents</code> (String template, AnyType model, String section, Object options)</p>
<pre><code>jtmpl.compileRules = [
{ # class="whatever, maybe other bindings... {{booleanVar}}
pattern: "(class=\"? [\\w \\. \\- \\s {{}}]*) {{ (#{ RE_IDENTIFIER }) }}$"
replaceWith: (pre, prop, model) ->
val = model[prop]
[ # Emit match, and class name if booleanVar
(pre.search('{') is -1 and pre or ' ')
(typeof val is 'boolean' and val and prop or '')
,
[]
]
echoReplaceWith: (pre, prop) ->
if pre.search('{') > - 1 then " {{#{ prop }}}" else null
bindingToken: (pre, prop) -> "class=#{ prop }"
}
{ # onevent={{func}}
pattern: "on(#{ RE_IDENTIFIER }) = {{ (#{ RE_IDENTIFIER }) }}$"
replaceWith: -> ['', []]
bindingToken: (event, handler) -> "on#{ event }=#{ handler }"
}
{ # attr={{prop}}
pattern: "(#{ RE_IDENTIFIER }) = {{ (#{ RE_IDENTIFIER }) }}$"
replaceWith: (attr, prop, model) ->
val = model[prop]
# null?
if not val? or val is null
['', []]
# boolean?
else if typeof val is 'boolean'
[(if val then attr else ''), []]
# quoted value
else
["#{ attr }=\"#{ val }\"", []]
bindingToken: (attr, prop) -> "#{ attr }=#{ prop }"
}
{ # {{^inverted_section}}
pattern: "{{ \\^ (#{ RE_IDENTIFIER }) }}$"
wrapper: 'defaultSection'
contents: (template, model, section, options) ->
val = model[section]
# Sequence?
if Array.isArray(val)
[ # template as HTML comment
"<!-- ^ #{ multiReplace(template, options.delimiters, options.compiledDelimiters) } -->"
# Render body if array empty
if not val.length then jtmpl(template, model) else ''
,
[]
]
else
[ jtmpl(template, model),
if val then [['style', 'display:none']] else []
]
bindingToken: (section) -> "^#{ section }"
}
{ # {{#section}}
pattern: "{{ \\# (#{ RE_IDENTIFIER }) }}$"
wrapper: 'defaultSection'
contents: (template, model, section, options) ->
val = model[section]
# Sequence?
if Array.isArray(val)
[ # template as HTML comment
"<!-- # #{ multiReplace(template, options.delimiters, options.compiledDelimiters) } -->"
# Render body for each item
(jtmpl(template, item, null, { asArrayItem: true }) for item in val).join(''),
[]
]
# Context?
else if typeof val is 'object'
# Render body using context
[ jtmpl(template, val),
[]
]
else
[ jtmpl(template, model),
if not val then [['style', 'display:none']] else []
]
bindingToken: (section) -> "##{ section }"
}
{ # {{&unescaped_var}}
pattern: "{{ & (#{ RE_IDENTIFIER }) }}$"
wrapper: 'defaultVar'
replaceWith: (prop, model) -> [prop is '.' and model or model[prop], []]
bindingToken: (prop) -> prop
}
{ # {{var}}
pattern: "{{ (#{ RE_IDENTIFIER }) }}$"
wrapper: 'defaultVar'
replaceWith: (prop, model) -> [escapeHTML(prop is '.' and model or model[prop]), []]
bindingToken: (prop) -> prop
}
]</code></pre>
<h3 id="bind-rules">Bind rules</h3>
<p>Matching is done on tokenized data-jt items</p>
<p><code>react</code> signature:</p>
<p>Function void (AnyType val) <code>react</code>
(DOMElement node, String for each pattern group, AnyType model)</p>
<pre><code>bindRules = [
{ # value/checked/selected=var
pattern: "(value | checked | selected) = (#{ RE_IDENTIFIER })",
react: (node, attr, prop, model) ->
# attach DOM reactor
# first select option?
if node.nodeName is 'OPTION' and node.parentNode.querySelector('option') is node
node.parentNode.addEventListener('change', ->
idx = 0
for option in node.parentNode.children
if option.nodeName is 'OPTION'
model[prop] = option.selected
idx
)
# radio group?
if node.type is 'radio' and node.name
node.addEventListener('change', ->
if node[attr]
for input in document.querySelectorAll("input[type=radio][name=#{ node.name }]")
if input isnt node
input.dispatchEvent(new Event('change'))
model[prop] = node[attr]
)
# text input?
if node.type is 'text'
node.addEventListener('input', -> model[prop] = node[attr])
# other inputs
else
node.addEventListener('change', -> model[prop] = node[attr])
# return model reactor
(val) -> if node[attr] isnt val then node[attr] = val
}
{ # class=var
pattern: "class = (#{ RE_IDENTIFIER })",
react: (node, prop, model) ->
(val) -> (val and addClass or removeClass)(node, prop)
}
{ # attr=var
pattern: "(#{ RE_IDENTIFIER }) = #{ RE_IDENTIFIER }",
react: (node, attr) ->
(val) -> if node[attr] isnt val then node[attr] = val
}
{ # var
pattern: "#{ RE_IDENTIFIER }",
react: (node) ->
(val) -> node.innerHTML = val
}
]</code></pre>
<h2 id="compile-rules-processor">Compile rules processor</h2>
<h3 id="compile-routine">Compile routine</h3>
<p>Tokenize template and apply each rule on tokens.
Rules can be inline or recursive, end block is hardcoded as "{{/block}}".
Current delimiters are respected.</p>
<p>String template
AnyType model
String openTag
Boolean echoMode
Array delimiters
Boolean asArrayItem</p>
<pre><code>jtmpl.compile = (template, model, openTag, echoMode, options, asArrayItem) ->
tokenizer = regexp("{{ (\/?) (#{ RE_ANYTHING }) }}", options.delimiters)
result = ''
pos = 0
while (token = tokenizer.exec(template))
# End block?
if token[1]
if token[2] isnt openTag
throw new Error(openTag and
":( expected {{/#{ openTag }}}, got {{#{ token[2] }}}" or
":( unexpected {{/#{ token[2] }}}")
# Exit recursion
return result template.slice(pos, tokenizer.lastIndex - token[0].length)
slice = template.slice(Math.max(0, pos - 128), tokenizer.lastIndex)
# Process rules
for rule in jtmpl.compileRules
match = regexp(rule.pattern, options.delimiters).exec(slice)
if match
# accumulate output
result = template.slice(pos, tokenizer.lastIndex - match[0].length)
# inject token in data-jt attr
htagPos = lastOpenedHTMLTag(result)
bindingToken = rule.bindingToken(match.slice(1)...)
# inline tag or section?
if rule.replaceWith?
if echoMode
result = rule.echoReplaceWith?(match.slice(1)...) or match[0]
else
[replaceWith, wrapperAttrs] =
rule.replaceWith(match.slice(1).concat([model])...)
if htagPos is -1 and rule.wrapper?
# wrapping needed
tag = options[rule.wrapper]
result = injectTagBinding("<#{ tag }>#{ replaceWith }</#{ tag }>", bindingToken, wrapperAttrs)
else
result = replaceWith
result = result.slice(0, htagPos) injectTagBinding(result.slice(htagPos), bindingToken, wrapperAttrs)
pos = tokenizer.lastIndex
else
# Recursively get nested template (echoMode=on)
tmpl = jtmpl.compile(
template.slice(tokenizer.lastIndex),
model, match[1], true, options)
# Skip block contents
tokenizer.lastIndex = tmpl.length
# Match close block token
closing = tokenizer.exec(template)
pos = tokenizer.lastIndex
if echoMode
result = token[0] tmpl closing[0]
else
[contents, wrapperAttrs] = rule.contents(tmpl, model, match[1], options)
if htagPos is -1
tag = options[rule.wrapper]
result = injectTagBinding("<#{ tag }>#{ contents }</#{ tag }>", bindingToken, wrapperAttrs)
else
result = (
result.slice(0, htagPos)
injectTagBinding(result.slice(htagPos), bindingToken, wrapperAttrs)
contents.trim()
)
# Match was found, skip other rules
break
result = template.slice(pos)
# Return accumulated output
if options.asArrayItem
# enclose in defaultSectionItem HTML tag if needed
if isValidHTMLTag(result)
result
else
tag = options.defaultSectionItem
"<#{ tag }>#{ result }</#{ tag }>"
else
result</code></pre>
<h3 id="compiling-stage-supporting-utilities">Compiling stage supporting utilities</h3>
<p>String addTagBinding(String, String)</p>
<p>Inject token in HTML element data-jt attribute.
Create attribute if not existent.
wrapperAttrs is array of pairs [attribute, value] to inject in element</p>
<pre><code>injectTagBinding = (template, token, wrapperAttrs) ->
# group 1: 'data-jt' inject position
# group 2: token inject position, if attribute exists
# group 3 (RE_DATA_JT): existing 'data-jt' value
match = regexp("^ (#{ RE_SPACE } < #{ RE_IDENTIFIER }) (#{ RE_ANYTHING }) #{ RE_DATA_JT }").exec(template)
attrLen = (match[3] or '').length
pos = match[1].length match[2].length attrLen
# inject, return result
( template.slice(0, pos)
( if token
( if attrLen
(if match[3].trim() is 'data-jt="' then '' else ' ') token
else
' data-jt="' token '"'
)
else
''
)
(" #{ pair[0] }=\"#{ pair[1] }\"" for pair in wrapperAttrs).join('')
template.slice(pos)
)</code></pre>
<p>Int lastOpenedHTMLTag(String)</p>
<p>Return index of the last opening, maybe opened (no close bracket), HTML tag
followed by end of string, or -1, if no such exists</p>
<pre><code>lastOpenedHTMLTag = (template) ->
template.trimRight().search(regexp("< #{ RE_IDENTIFIER } [^>]*? >?$"))</code></pre>
<p>Boolean isValidHTMLTag(String)</p>
<p>Check if contents is properly formatted closed HTML tag</p>
<pre><code>isValidHTMLTag = (contents) ->
!!contents.trim().match(regexp("^<(#{ RE_IDENTIFIER }) #{ RE_SPACE }
[^>]*? > #{ RE_ANYTHING } </\\1>$ | < [^>]*? />$")
)</code></pre>
<h2 id="bind-rules-processor">Bind rules processor</h2>
<p>void <code>bind</code> (DOMElement root, AnyType model)</p>
<p>Walk DOM and setup reactors on model and nodes.</p>
<pre><code>jtmpl.bind = (root, model) ->
itemIndex = 0
nodeContext = null
# iterate children
for node in root.childNodes
switch node.nodeType
when node.ELEMENT_NODE
;
when node.COMMENT_NODE
;
# return node
node</code></pre>
<h2 id="supporting-code">Supporting code</h2>
<h3 id="array-shortcuts">Array shortcuts</h3>
<pre><code>ap = Array.prototype
apslice = ap.slice
appop = ap.pop
appush = ap.push
apreverse = ap.reverse
apshift = ap.shift
apunshift = ap.unshift
apsort = ap.sort</code></pre>
<h3 id="functional-utilities">Functional utilities</h3>
<p>Function curry(Function f, AnyType frozenArg1, AnyType frozenArg2, ...)</p>
<pre><code>curry = ->
args = apslice.call(arguments)
->
args2 = apslice.call(arguments)
args[0].apply(@, args.slice(1).concat(args2))</code></pre>
<p>Function compose(Function f, Function g)</p>
<pre><code>compose = (f, g) -> -> f(g.apply(@, apslice.call(arguments)))</code></pre>
<h3 id="object-utilities">Object utilities</h3>
<p>Extend an object with given properties</p>
<pre><code>extend = (obj, props) ->
for k, v of props
obj[k] = v
obj</code></pre>
<h3 id="regular-expression-utilities">Regular expression utilities</h3>
<p>String escapeRE(String s)</p>
<p>Escape regular expression characters</p>
<pre><code>escapeRE = (s) -> (s '').replace(/([.?* ^$[\]\\(){}|-])/g, '\\$1')</code></pre>
<p>RegExp regexp(String src, Object options)</p>
<p>Replace mustaches with given delimiters, strip whitespace, return RegExp</p>
<pre><code>regexp = (src, delimiters) ->
# strip whitespace
src = src.replace(/\s /g, '')
new RegExp((if delimiters then src
.replace('{{', escapeRE(delimiters[0]))
.replace('}}', escapeRE(delimiters[1]))
else src)
, 'g')</code></pre>
<h3 id="string-utilities">String utilities</h3>
<p>String escapeHTML(String val)</p>
<p>Replace HTML special characters</p>
<pre><code>escapeHTML = (val) ->
(val? and val or '')
.toString()
.replace /[&"<>\\]/g, (s) -> {
'&': '&amp;'
'\\': '\\\\'
'"': '\"'
'<': '&lt;'
'>': '&gt;'
}[s]</code></pre>
<p>String multiReplace(String template, Array from, Array to)</p>
<p>Replace <code>from</code> literal strings with <code>to</code> strings in template</p>
<pre><code>multiReplace = (template, from, to) ->
for find, i in from
template = template.replace(regexp(escapeRE(find)), escapeRE(to[i]))
template</code></pre>
<h3 id="dom-utilities">DOM utilities</h3>
<p>DOMElement createSectionItem (DOMElement parent, AnyType context)</p>
<pre><code>createSectionItem = (parent, context) ->
element = document.createElement('body')
element.innerHTML = jtmpl(parent.getAttribute('data-jt-1') or '', context)
element = element.children[0]
jtmpl(element, element.innerHTML, context, { rootModel: model })
element</code></pre>
<h3 id="binding-utilities">Binding utilities</h3>
<p>void initBindings(Object context, String prop)</p>
<p>Create slots for property value and change reactor functions.
Setter notifies all reactors.</p>
<pre><code>initBindings = (context, prop) ->
if not context["__#{ prop }_bindings"]
Object.defineProperty(context, "__#{ prop }_bindings",
enumerable: false
writable: true
value: []
)
Object.defineProperty(context, "__#{ prop }",
enumerable: false
writable: true
value: context[prop]
)
Object.defineProperty(context, prop,
get: -> this["__#{ prop }"]
set: (val) ->
this["__#{ prop }"] = val
reactor.call(this, val) for reactor in this["__#{ prop }_bindings"]
)</code></pre>
<p>void bindArrayToNodeChildren(Array array, DOMElement node)</p>
<p>Bind an array to DOM node,
so when array is modified, node children are updated accordingly.</p>
<p>Array is augmented by attaching listeners on existing indices
and setting a proxy for each mutable operation.
<code>createSectionItem</code> is used for creating new items.</p>
<pre><code>bindArrayToNodeChildren = (array, node) ->
# array already augmented?
if not array.__garbageCollectNodes
# it's possible for a referenced node to be destroyed. free the reference
array.__garbageCollectNodes = ->
i = this.__nodes.length
while --i
if not this.__nodes[i].parentNode
this.__nodes.splice(i, 1)
array.__removeEmpty = ->
if not this.length then node.innerHTML = ''
array.__addEmpty = ->
if not this.length then node.innerHTML = jtmpl(node.getAttribute('data-jt-0') or '', {})
# Mutable array operations
array.pop = ->
this.__removeEmpty()
this.__garbageCollectNodes()
node.removeChild(node.children[node.children.length - 1]) for node in this.__nodes
appop.apply(this, arguments)
appop.apply(this.__values, arguments)
this.__addEmpty()
array.push = (item) ->
this.__removeEmpty()
this.__garbageCollectNodes()
node.appendChild(createSectionItem(node, item)) for node in this.__nodes
appush.apply(this, arguments)
len = this.__values.length
result = appush.apply(this.__values, arguments)
bindProp(item, len)
result
array.reverse = ->
this.__removeEmpty()
this.__garbageCollectNodes()
result = apreverse.apply(this.__values, arguments)
for node in this.__nodes
node.innerHTML = ''
for item, i in this.__values
node.appendChild(createSectionItem(node, item))
bindProp(item, i)
this.__addEmpty()
result
array.shift = ->
this.__removeEmpty()
this.__garbageCollectNodes()
apshift.apply(this, arguments)
result = apshift.apply(this.__values, arguments)
for node in this.__nodes
node.removeChild(node.children[0])
for item, i in this.__values
bindProp(item, i)
this.__addEmpty()
result
array.unshift = ->
this.__removeEmpty()
this.__garbageCollectNodes()
for item in apslice.call(arguments).reverse()
for node in this.__nodes
node.insertBefore(createSectionItem(node, item), node.children[0])
apunshift.apply(this, arguments)
result = apunshift.apply(this.__values, arguments)
for item, i in this.__values
bindProp(item, i)
this.__addEmpty()
result
array.sort = ->
this.__removeEmpty()
this.__garbageCollectNodes()
apsort.apply(this, arguments)
result = apsort.apply(this.__values, arguments)
for node in this.__nodes
node.innerHTML = ''
for item, i in array
node.appendChild(createSectionItem(node, item)) for node in this.__nodes
bindProp(item, i)
this.__addEmpty()
result
array.splice = (index, howMany) ->
this.__removeEmpty()
this.__garbageCollectNodes()
for node in this.__nodes
for i in [0...howMany]
node.removeChild(node.children[index])
for item in apslice.call(arguments, 2)
node.insertBefore(createSectionItem(node, item), node.children[index])
bindProp(item, index)
apsplice.apply(this, arguments)
apsplice.apply(this.__values, arguments)
this.__addEmpty()
# Bind property
bindProp = (item, i) ->
array.__values[i] = item
Object.defineProperty(array, i,
get: -> this.__values[i]
set: (val) ->
this.__garbageCollectNodes()
this.__values[i] = val
node.replaceChild(createSectionItem(node, val), node.children[i]) for node in this.__nodes
)
# bound nodes
Object.defineProperty(array, '__nodes',
enumerable: false
writable: true
value: []
)
# onchange handlers for each item
Object.defineProperty(array, '__values',
enumerable: false
writable: true
value: []
)
for item, i in array
bindProp(item, i)
if array.__nodes.indexOf(node) is -1 then array.__nodes.push(node)
array</code></pre>
<footer>
Copyright © 2013 Atanas Minev, <a href="LICENSE">MIT license</a>
</footer>
</div>
<script src="js/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<script src="js/jtmpl.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-43285803-1', 'jtmpl.com');
ga('send', 'pageview');
</script>
</body>
</html>