2016-11-16 55 views
0

我刚刚开始学习riotJS,无法弄清楚标签(实例)之间的通信是如何完成的。我创建了一个简单的例子。可以说我有以下标签: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文件中获取到标签实例的引用,这样我可以调用它的trigger()方法?我认为mount()方法返回一个实例,但是如果你想稍后获取一个参考呢?

+0

你有没有检查出http://stackoverflow.com/questions/31435078/riotjs-how-to-pass-events-between-subtags-using-observable-pattern/32096712#32096712 – jbrown

回答

2

要获取标签实例的引用,您必须执行此操作。标签将是一个包含标签的数组。

riot.compile(function() { 
    tags = riot.mount('*') 
    console.log('root tag',tags[0]) 
    }) 

如果您要访问的孩子,让说,维达是父标签,莱娅和卢克儿童标记

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']) 
    }) 

但我会建议为标签的通信可观察的模式。你会很容易

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.store全局对象,发送和接收消息

活生生的例子http://plnkr.co/edit/QWXx3UJWYgG6cRo5OCVY?p=preview

在你的情况下,使用riot.store是一样的,也许你需要使用自不失去上下文参考

<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') 
+0

谢谢,正是我在找什么对于! – Stefan

0

如果你不想使用全球商店,看看RiotComponent。它以直观的方式实现元素之间的通信。

它基本上允许将方法,可侦听属性和事件添加到元素,以便父元素可以使用这些元素。