我不太确定我是否正确理解了可观察对象的工作方式以及如何从挂载的标签中获取引用。我有一个组件。在这个组件中,我们有一个 组件 和一个 组件。目的是避免组件之间的耦合。因此,我希望我的搜索组件 在搜索完成(单击按钮)时触发一个事件。此事件应由 组件 捕获,该组件将根据搜索过滤集合数据。
index.html 文件使用以下方式加载标签:
index.html
riot.mount(".content", "page", null);
页面定义如下:
page.js
<page>
<!-- Search tag controls -->
<search id="searchTag"></search>
<!-- Collection data to display -->
<collection id="collectionTag"></collection>
</page>
组件脚本的简要定义如下:
search.js
var self = this;
riot.observable(self);
<!-- This function is called when the user click on the button. -->
self.filtering = function()
{
<!-- We get data from inputs -->
var info = Getting data from inputs;
<!-- Trigger the event hoping that someone will observe it -->
self.trigger("filterEvent", info);
}
如何让 组件 观察该事件?
在我看来,我应该能够从 page.js 中的search 标签 和collection 标签 获取引用。通过这样做,我可以像下面这样连接事件:
searchComponent = riot.mount('search');
collectionComponent = riot.mount('collection');
searchComponent.on('filterEvent', function()
{
<!-- Trigger function to filter collection data -->
collectionComponent.trigger('filterData');
});
现在我无法让它像那样工作。
在执行时,未定义 searchComponent 和 collectionComponent。
我还尝试通过使用this.searchTag
和this.collectionTag
获取这些组件的引用,而不是挂载它们,但在执行代码时,组件尚未安装,因此我没有得到对它们的引用。
有什么想法可以让它发挥作用吗?
最佳答案
受到@gius 给出的答案的启发,现在这是我在 RiotJS 中将事件从一个标签发送到另一个标签的首选方法。使用起来非常棒!
与@gius 方法的不同之处在于,如果您使用大量嵌套标签,将共享的 Observable 传递给每个标签是不够的,因为您需要一次又一次地将它传递给每个子标签(或调用带有困惑 this.parent 调用的子标签)。
定义一个简单的 Mixin,就像下面这样,它简单地定义了一个 Observable,这意味着您现在可以在任何您想要的标签中共享它。
var SharedMixin = {
observable: riot.observable()
};
将这一行添加到您的标签中..
this.mixin(SharedMixin);
现在,任何包含上述行的标签都可以触发事件,例如..
this.observable.trigger('event_of_mine');
..或接收这样的事件..
this.observable.on('event_of_mine',doSomeStuff());
在这里查看我的工作 jsfiddle http://jsfiddle.net/3b32yqb1/5/ .
关于javascript - RiotJS - 如何使用 Observable 模式在子标签之间传递事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31435078/