0

在我的一个模板中,我想从模型中获取一个整数并从中创建 html。我有一个名为value的Customer模型属性。从那个值我想把这个 html 注入到模板中:starRating3Customer

<i style="color: #dddddd" class="icon-star"></i>
<i style="color: #dddddd" class="icon-star"></i>
<i style="color: #dddddd" class="icon-star"></i>
<i style="color: #dddddd" class="icon-star-empty"></i>
<i style="color: #dddddd" class="icon-star-empty"></i>

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

4

1 回答 1

1

可能有很多解决方案可以做动态评分栏之类的事情,所以这是我的尝试。

星级评定组件

定义一个新组件(有关组件的更多信息,请参见此处),该组件包含星级评级的逻辑,并且最好的是它是可重用的。另请注意,评分栏将显示多少星是动态的,为简单起见,该数字在客户模型中定义(如下所示),但可能来自任何地方:

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,正如您将在演示中看到的那样,我们在模型中使用随机生成的信息(为简单起见):

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

也许这不是你之后的解决方案,但我想它会让你朝着正确的方向前进。

请参阅此处查看工作演示

希望能帮助到你。

于 2013-09-10T20:21:41.840 回答