forked from leonidas/transparency
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.coffee
More file actions
49 lines (40 loc) · 1.61 KB
/
context.coffee
File metadata and controls
49 lines (40 loc) · 1.61 KB
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
{before, after, chainable, cloneNode} = require './helpers'
Instance = require './instance'
# **Context** stores the original `template` elements and is responsible for creating,
# adding and removing template `instances` to match the amount of `models`.
module.exports = class Context
detach = chainable ->
@parent = @el.parentNode
if @parent
@nextSibling = @el.nextSibling
@parent.removeChild @el
attach = chainable ->
if @parent
if @nextSibling
then @parent.insertBefore @el, @nextSibling
else @parent.appendChild @el
constructor: (@el, @Transparency) ->
@template = cloneNode @el
@instances = [new Instance(@el, @Transparency)]
@instanceCache = []
render: \
before(detach) \
after(attach) \
chainable \
(models, directives, options) ->
# Cloning DOM elements is expensive, so save unused template `instances` and reuse them later.
while models.length < @instances.length
@instanceCache.push @instances.pop().remove()
# DOM elements needs to be created before rendering
# https://github.com/leonidas/transparency/issues/94
while models.length > @instances.length
instance = @instanceCache.pop() || new Instance(cloneNode(@template), @Transparency)
@instances.push instance.appendTo(@el)
for model, index in models
instance = @instances[index]
children = []
instance
.prepare(model, children)
.renderValues(model, children)
.renderDirectives(model, index, directives)
.renderChildren(model, children, directives, options)