如何访问 router/controller 中的模型数据?

How does one access model data in a router/controller?

请多多包涵,我是新手。

我一直在为这个问题伤透脑筋,最后才来这里。它是关于如何在路由加载时访问模型的数据。例如,当 /meals/2 加载时,我想要一个 运行 的函数,它使用该模型的背景图像字符串 属性 设置文档的背景。或者当 /meals 加载时,使用集合第一项的 属性 的函数。

任何有关 'the ember way' 的帮助都将不胜感激。

Menu.hbs

  {{#each meal in model}}
    <span {{action 'mealSelected' meal.image_large}}>
      {{#link-to 'menu.meal' meal tagName="li" class="meal-block" href="view.href"}}
        [...]
      {{/link-to}}
    </span>
  {{/each}}

<div id="meal-info-wrapper">

  {{outlet}}

</div>

型号:

export default DS.Model.extend({
  name: DS.attr('string'),
  image: DS.attr('string')
});

Router.js

export default Router.map(function() {
    this.route('about');
    this.route('menu', { path: '/' }, function() {
        this.route('meal', { path: '/meal/:id/:slug' });
    });
});

routes/menu.js

export default Ember.Route.extend({
  model: function() {
    return this.store.find('menu');
  },
  afterModel: function() {
    Ember.$(document).anystretch('temp-images/bg-1.png');
  }
});

例如,我想在 routes/menu.js 中做的是让模型提供图像 url。

如果我误解了什么,请纠正我,你想要做的是:

Change the background image of a DOM element based on a property found in each Model's record.

  1. 模型加载是一个异步操作,你想在确定数据加载后进行图像交换。您使用 afterModel 挂钩来保证这一点,但这还不够。
  2. 您想修改模板中的DOM,但您需要确保模板已经呈现。所以,DOM操作逻辑,不是放在afterModel里面,而是属于Views有的didInsertElement事件。

我建议您使用一个组件(它也是一个视图),例如:

  // your template
  {{#each meal in model}}
    {{meal-component content=meal}}
  {{/each}}

  // the meal-component
  didInsertElement: function() {
     var imgURLProperty = this.get('content.imgURLProperty');
     Ember.$(document).anystretch(imgURLProperty);
  }

当然,您不能复制粘贴任何内容。它只是向您展示了如何根据模型的属性修改模板的主要机制。

afterModel 仅在模型已解析且模型作为参数传递后才会 运行。因此,根据我对您的应用的理解,您可以将 routes/menu 示例调整为:

export default Ember.Route.extend({
  model: function() {
    return this.store.find('menu');
  },
  afterModel: function(model) {
    Ember.$(document).anystretch(model.get('firstObject.image'));
  }
});