【问题标题】:Emberjs loading multiple controllers into oneEmberjs 将多个控制器合二为一
【发布时间】:2014-07-29 02:36:54
【问题描述】:

场景
我目前有一个IndexRoute。我想将其他 3 个控制器加载到其中。这 3 个其他控制器称为 SportsNewsBusiness。我阅读了 embersjs 文档,它指出您需要在 IndexRoute 中实现 renderTemplate 挂钩,以便在索引中显示每个控制器。 http://emberjs.com/guides/routing/rendering-a-template/

完成后,我将其放入索引模板

{{ outlet sports }}
{{ outlet news }}
{{ outlet business }}

它们出现了,但是当我查看 EmberInspector 扩展时,SportsNewsBusiness 的单个模型没有加载。

问题
为什么这些SportsNewsBusiness 的模型没有加载到索引中?

查看我的代码示例的 JSBIN
http://jsbin.com/gecarido/1/edit

附加图片

【问题讨论】:

    标签: javascript ember.js ember-data


    【解决方案1】:

    只有在您通过 url 定义并点击路由时才会点击路由。

    例如,如果您这样定义路由器:

    Ember.Router.map(function(){
      this.resource('foo', function(){
        this.resource('bar');
      });
    });
    

    然后点击/foo/bar

    它会击中

    App.FooRoute = Em.Route.extend({
    
    });
    

    App.BarRoute = Em.Route.extend({
    
    });
    

    如果您只想从根 url 中获取所有内容,不妨从应用程序模型挂钩中全部返回。

    App.ApplicationRoute = Ember.Route.extend({
      model: function() {
        return {
          colors: ['red', 'yellow', 'blue'],
          news: ['Europe', 'Asia', 'America'],
          business: ['Markets', 'Finance', 'Stocks'],
          sports: ['golf', 'hockey', 'football']
        };
      }  
    });
    

    然后您可以使用模板中的render 并为其提供模板名称和模型。

    <script type="text/x-handlebars">
      <h2>Welcome to Ember.js</h2>
    
      <ul>
      {{#each item in colors}}
        <li>{{item}}</li>
      {{/each}}
      </ul>
    
      <br>
      {{render 'sports' sports}}
      <br>
      {{render 'news' news}}
      <br>
      {{render 'business' business}}
      <br>
      {{outlet}}
    </script>
    

    http://jsbin.com/gecarido/3/edit

    【讨论】:

    • 这是一个解决方案,但您的反馈让我开始搜索以使该设计更加模块化。
    【解决方案2】:

    我有另一个答案,可以用更模块化的方法解决这个问题

    在我原来的解决方案中
    我假设每个控制器都有自己的路由,并且该路由将处理返回该控制器的数据。因此,如果您包含所有 3 个控制器,它们每个都将处理获得它自己的模型。但我有错误的假设。我重新阅读了 embersjs http://emberjs.com/guides/controllers/ 中的 “note on coupling”

    所以我从该文档中得到的是该路由负责获取所有模型,但您必须告诉它将其分配给该路由中的其他控制器。我还阅读了模型和固定装置http://emberjs.com/guides/models/the-fixture-adapter/

    我的新解决方案

    • 摆脱了额外的路线(暂时)
    • 添加了带有夹具数据的 Ember 数据
    • 我仍然保留 {{ outlet }} 我使用了 IndexRoute中的“setupController”钩子连接外部 具有正确数据的控制器。 这是关键

    采用这种方法的原因是我可能想在 UI 的其他地方使用“新闻”、“商业”、“体育”这些控制器。我甚至可以在未来建立自己的路线,我认为现在使用 ember 数据和模型会有所帮助。

    查看 JSBIN 解决方案
    请注意,此解决方案适用于我的桌面,但 JSBIN 抛出了一些奇怪的 Script 0 错误 http://jsbin.com/gecarido/5/edit

    【讨论】:

      猜你喜欢
      • 2021-02-18
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      • 2010-12-28
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多