2016-11-16 26 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。它以直觀的方式實現元素之間的通信。

它基本上允許將方法,可偵聽屬性和事件添加到元素,以便父元素可以使用這些元素。