LOGO

Messaging from Dynamic Child Components

Edit

Child components can be created dynamically using the runtime data. dispatch/message won’t work cause there’s no parent-child relationship between the current component and the newly created one. For a fix, all we need to do is building the relationship.

example

Here’s a example in which we need to create a tree of components from the tree structure in the data, and pass messages between the parent and children:

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
const Child = san.defineComponent({
template: `
<div class="child">
{{name}}<button on-click="sendMsg">send msg</button>
</div>
`,
sendMsg() {
this.dispatch('child-msg', this.data.get('msg'));
}
});

const Parent = san.defineComponent({
template: `
<div class="parent" style="border: 1px solid red">
I am parent
<button on-click="addChild">
add child
</button>
{{childMsg}}
</div>`,

addChild() {

const childs = this.data.get('childs');
const parentEl = this.el;

childs.forEach(child => {

let childIns = new Child({
parent: this,
data: child
});

childIns.attach(parentEl);
this.children.push(childIns);

});
},

messages: {
'child-msg': function(arg) {
this.data.set('childMsg', arg.value);
}
}
});

const parent = new Parent({
data: {
childs: [{
name: 'I am child1',
msg: 'child1 send msg'
}, {
name: 'I am child2',
msg: 'child2 send msg'
}]
}
});

parent.attach(document.body);

Demo

See the Pen QMMZPV by zhanfang (@zhanfang) on CodePen.