简体   繁体   English

具有自己数据源的可重用余烬组件

[英]Reusable ember component with its own data source

I have a dropdown <select> -based component that I'd like to be able to drop into any template in the hierarchy of my ember app. 我有一个基于下拉列表的<select>组件,希望将其放入ember应用程序层次结构中的任何模板中。

This displays a list of all the Articles (the model) on the site. 这将显示该站点上所有文章(模型)的列表。 Whenever I use this component though, the route that I'm in needs to load the data and get passed to the template. 但是,无论何时使用此组件,我所处的路由都需要加载数据并传递给模板。

Question : How can I load this data once and only when the component is rendered? 问题:如何并且仅在渲染组件时一次加载此数据?

Also I've been reading this and still have yet to come up with a good solution. 另外,我一直在阅读此书 ,但仍未提出好的解决方案。 I'd like the component to provide the data source, but that seems to be frowned upon. 我希望该组件提供数据源,但这似乎不被接受。

Would it be terrible to just do an ajax request in my component pre-render? 仅在组件预渲染中发出ajax请求会很糟糕吗?

If you are going to need data preloaded then you can use the initializers to do that for you. 如果您需要预加载数据,则可以使用initializers来完成。 You can use this data and inject to any controller , route or all of them if you want. 您可以使用此数据,并根据需要注入到任何控制器,路由或所有它们。 This is a more maintainable way. 这是一种更可维护的方法。

For your case you can have a particular controller have articles injected into. 对于您的情况,您可以让特定的控制器插入文章。 Then use this controller data using needs in other required controllers and thus into components. 然后根据needs在其他所需控制器中使用此控制器数据,从而将其用作组件。

In this way you have data available for all instance of component. 这样,您便拥有了可用于所有组件实例的数据。 Passing an store object inside the component is mostly an anti-pattern ( depends upon use cases though ) . 在组件内部传递存储对象通常是一种反模式 尽管取决于用例

Component should be free from headache of data gathering and should focus on logic and presentation. 组件应该摆脱数据收集的麻烦,并且应该专注于逻辑和表示。

If want to know more about how to use initializers you can find it here 如果想更多地了解如何使用initializers ,可以在这里找到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM