-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
52 lines (42 loc) · 1.54 KB
/
index.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
var assert = require('nanoassert')
var Context = require('../').Context
// spawn component contexts on demand and optionally discard on unload
// (fn, obj?) -> fn
module.exports = function init (identity, opts) {
assert(typeof identity === 'function', 'fun-component: identity should be a function')
opts = opts || {}
var cache = opts.cache || {}
return function spawn (source) {
var name = source._name
var render = source._render
var events = source._events
var args = Array.prototype.slice.call(arguments, 1)
var id = identity.apply(undefined, args)
assert(typeof id === 'string', 'fun-component: identity should return a string')
var ctx = typeof cache.get === 'function' ? cache.get(id) : cache[id]
if (!ctx) {
// spawn a new context
ctx = new Context([name, id].join('_'), render)
if (typeof cache.set === 'function') cache.set(id, ctx)
else cache[id] = ctx
if (!opts.persist) {
// remove context from cache on unload
ctx.on('unload', function () {
if (typeof cache.remove === 'function') cache.remove(id)
else delete cache[id]
})
}
// copy over all lifecycle event listeners to the new context
var keys = Object.keys(source._events)
for (var i = 0, len = keys.length; i < len; i++) {
addEventListeners(ctx, keys[i], events[keys[i]])
}
}
return ctx
}
}
function addEventListeners (ctx, event, listeners) {
for (var i = 0, len = listeners.length; i < len; i++) {
ctx.on(event, listeners[i])
}
}