简体   繁体   English

Ember js 2 计数相关字段(hasMany)

[英]Ember js 2 counts related field (hasMany)

I feel confused with the access to ember model in the controller using a compute property.我对使用计算属性在控制器中访问 ember 模型感到困惑。

My issue: I'm trying to create two properties one to count the related objects of hasMany field marcanet , and second limit the size of this property to only display n elements.我的问题:我正在尝试创建两个属性,一个是计算 hasMany 字段marcanet的相关对象,第二个是将此属性的大小限制为仅显示n元素。

First scenery computes property on Model:第一个风景计算模型的属性:

import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { hasMany } from 'ember-data/relationships';
import Ember from 'ember';

export default Model.extend({
    client: attr('string'),
    figure: attr('string'),
    marcanet: hasMany('marcanet'),
    title: attr('string'),
    tm_type: attr('string'),

    total: function() {
        return this.get('marcanet.length');
    }.property('model')
    // issue i can't render it on my template as {{model.total}}
    // so, I can't understand if it is computed right.
});

Second scenery moving to the Controller.第二个风景移动到控制器。

Here I only can access to the main object Trademark这里我只能访问主对象Trademark

import Ember from 'ember';

export default Ember.Controller.extend({
    // It works
    sliceTrademarks: function() {
        return this.get('model').slice(0, 5);
    }.property('model'),
    // It works
    totalTrademarks: function() {
        return this.get('model.length');
    }.property('model'),

    // It throws me an error TypeError: this.get(...) is undefined
    sliceMarcanet: function() {
        return this.get('model.marcanet').slice(0, 2);
    }.property('model'),
    // It only give me an empty result
    totalMarcanet: function() {
        return this.get('model.marcanet.length');
    }.property('model')
});

I to solve my issue I did the following,为了解决我的问题,我做了以下事情,

I used a compute property on my model to get the size of the related objects,我在我的模型上使用了一个计算属性来获取相关对象的大小,

// Thanks for the advice @torazaburo 
relatedTotal: Ember.computed.alias('marcanet.length')

And I created a helper called limit to do the limit task我创建了一个名为 limit 的助手来完成限制任务

// helpers/limit.js
import Ember from 'ember';

export function limit(params, { limitObject, size }) {
  return limitObject.slice(0, size);
}
export default Ember.Helper.helper(limit);

and my template looks like this.我的模板看起来像这样。

// template/index.hbs
{{#each model as |trademark|}}
    {{trademark.id}} limit to 2 records<br>
  <ul>
  {{#each (limit limitObject=trademark.marcanet size=2) as |related|}}
    <li>{{related.expediente}}</li>
  {{/each}}
  </ul>
{{/each}}

Note: It works on Ember 2.4.5, see my example注意:它适用于 Ember 2.4.5,参见我的示例

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

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