我刚刚开始学习riotJS,无法弄清楚标签(实例)之间的通信是如何完成的。我创建了一个简单的例子。假设我有以下标签:
<warning-message>
<div>{ warning_message }</div>
<script>
this.warning_message = "Default warning!";
this.on('updateMessage', function(message){
this.warning_message = message;
});
</script>
</warning-message>
我想我可以使用tagInstance.trigger('updateMessage', someData)
告诉标签实例更新消息,但我如何从我的主js文件中获得对标签实例的引用,以便我可以调用它的触发器()方法?我认为mount()方法返回一个实例,但如果你想获得一个引用以后怎么办?
要获取标签实例的引用,您必须这样做。Tags将是一个包含标签的数组。
riot.compile(function() {
tags = riot.mount('*')
console.log('root tag',tags[0])
})
如果你想访问子元素,比如vader是parent标签,leia和luke是children标签
riot.compile(function() {
tags = riot.mount('*')
console.log('parent',tags[0])
console.log('children',tags[0].tags)
console.log('first child by name',tags[0].tags.luke)
console.log('second child by hash',tags[0].tags['leia'])
})
但是我将推荐标签通信的可观察模式。
´s容易1)创建store.js文件var Store = function(){
riot.observable(this)
}
2)在索引中将其添加到全局暴乱对象,因此它将在任何地方被访问
<script type="text/javascript">
riot.store = new Store()
riot.mount('*')
</script>
3)然后在任何标签中都可以有:
riot.store.on('hello', function(greeting) {
self.hi = greeting
self.update()
})
4)在其他标签中有:
riot.store.trigger('hello', 'Hello, from Leia')
所以你使用riot进行交流。存储全局对象,发送和接收消息
实例http://plnkr.co/edit/QWXx3UJWYgG6cRo5OCVY?p=preview
在你的例子中,使用暴乱。Store也是一样,可能你需要使用self来不丢失上下文引用
<script>
var self = this
this.warning_message = "Default warning!";
riot.store.on('updateMessage', function(message){
self.warning_message = message;
});
</script>
然后从任何其他标签调用
riot.store.trigger('updateMessage', 'Hello')
如果你不想使用全局存储,可以看看RiotComponent。它使元素之间的通信以直观的方式。
它基本上允许方法,listenable属性和事件被添加到元素中,这样父元素就可以使用这些