【问题标题】:RiotJs: communication with a tag instanceRiotJs:与标签实例的通信
【发布时间】:2016-11-16 16:12:10
【问题描述】:

我才刚刚开始学习 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() 方法会返回一个实例,但是如果您想稍后获取引用怎么办?

【问题讨论】:

标签: javascript riot.js


【解决方案1】:

要获得标签实例的引用,您必须这样做。 tags 将是一个带有标签的数组。

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

如果你想访问孩子,假设 vader 是父标签,leia 和 luke 孩子标签

  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)在索引中将它添加到全局 riot 对象中,这样它就可以在任何地方访问

   <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 是一样的,可能你需要使用 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')

【讨论】:

  • 谢谢,正是我想要的!
【解决方案2】:

如果您不想使用全局存储,请查看RiotComponent。它以直观的方式实现元素之间的通信。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 2012-02-04
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多