视图逻辑在ember.js中的位置是什么?

时间:2013-09-10 19:35:02

标签: ember.js

在我的一个模板中,我想从模型中取一个整数并从中创建html。我有一个名为Customer的{​​{1}}模型属性,其值为starRating。从该值我想将此html注入3模板:

Customer

我在哪里放置创建该html的逻辑?我尝试将一个计算属性添加到视图中,但整个函数定义以明文形式注入页面。对于这个只在页面中使用过一次的小片段,创建一个帮助器/组件似乎过分了。

1 个答案:

答案 0 :(得分:1)

可能有很多解决方案可以像动态评级栏那样做,所以这是我的尝试。

StarRatingComponent

定义一个新组件(有关组件的更多信息,请参阅here),其中包含星级评定的逻辑,其中最重要的是它可重复使用。另请注意,根据评级栏显示的星数,它是动态的,为了简单起见,该数字在客户模型中定义(如下所示),但可能来自任何地方:

App.StarRatingComponent = Ember.Component.extend({
  maxStars: 0,
  starRating: 0,
  stars: [],
  didInsertElement: function() {
    this.initStars();
    this.setStars();
  },
  initStars: function() {
    var stars = [], i = 0;
    for(i = 0; i < this.get('maxStars'); i++){
      stars.pushObject(Em.Object.create({empty:true}));
    }
    this.set('stars', stars);
  },
  setStars: function() {
    var counts = [], i = 0;
    for(i = 0; i < this.get('starRating'); i++){
      this.get('stars').objectAt(i).set('empty', counts[i]);
    }
  }
});

伪客户模型

我刚刚定义了一个伪模型,因为我不知道你的样子是什么样的,它包含了这些信息:

App.Customer = DS.Model.extend({
  starRating: DS.attr('number'),
  maxStarRating: DS.attr('number', {defaultValue: 5})
});

星级评分组件模板

现在让我们使用一个模板备份我们的评级栏,该模板将根据组件的参数化进行渲染(详见下文)

<script type="text/x-handlebars" id="components/star-rating">
  {{#each star in stars}}
    <i style="color: #AA2567" {{bindAttr class=":glyphicon star.empty:glyphicon-star-empty:glyphicon-star"}}></i>
  {{/each}}
</script>

实施

现在已经完成了所有设置,实际的实现非常简单,使用以下行:

{{star-rating starRating=customer.starRating maxStars=customer.maxStarRating}}

我们渲染出提供评级值starRating的组件以及动态条应使用maxStars呈现的星数,正如您将在demo中看到的那样,我们使用随机生成的信息(为简单起见,在我们的模型中:

...
{{#each customer in model}}
  <li>Rating: {{customer.starRating}}
  {{star-rating starRating=customer.starRating maxStars=customer.maxStarRating}}</li>
{{/each}}
...

也许这不是你所追求的解决方案,但我想你可以在正确的方向上做到这一点。

请参阅此处了解正常工作demo

希望它有所帮助。