无法在控制器中对模型哈希调用forEach

时间:2016-05-12 19:53:52

标签: arrays ember.js controller computed-properties

我有一条名为tickets的路线,它的模型设置如此

model() {
  return Ember.RSVP.hash({
    event: null,
    tickets: null
  });
},
actions: {
  didTransition(){
    if(!this.controller.get('model.length')){
      new Ember.RSVP.hash({
        event: this.modelFor('events.event'),
        tickets: this.store.query('ticket',{user_id:this.get('user.user.user_id'),event_code:this.modelFor('events.event').get('event_code')})
      }).then((hash)=>{
        if(!hash.tickets.get('length')){
          this.controller.set('noTickets',true);
        }
        this.controller.set('model',hash);
      });
    }
  }
}

模板设法在model.tickets

中循环遍历这些{{#each}}

在我的控制器中,我尝试设置groupBy计算,但在我的计算中是我得到错误

ticketsByPurchase: Ember.computed('model.tickets.[].ticket_purchase_code',function(){
    let tickets = this.get('model.tickets');
    tickets.forEach(function(ticket){
      console.log(ticket);
    });
  })

2 个答案:

答案 0 :(得分:2)

尝试防止被迭代的model.tickets,在计算属性中使用类似的东西:

if(!tickets){
  return Ember.A()
}else{
  //your forEach code here
}

或在你的路线中:

  }).then((hash)=>{
    if(!hash.tickets.get('length')){
      this.controller.set('noTickets',true);
      hash.tickets = Ember.Array([])
      this.controller.set('model',hash);
    }else{
      this.controller.set('model',hash);
    }
  });

答案 1 :(得分:0)

this.controller.get('model.length')始终为null,因为model是哈希值,而不是数组。此外didTransition不是一个动作,它是一个常规函数,因此如果在动作哈希中定义它可能不会触发。

我建议删除对didTransition的调用,并像你这样在模型钩子中执行所有逻辑:

model() {
  let event = this.modelFor('events.event');
  let event_code = event.get('event_code');

  // this probably does not work, you have to get the user
  // from another route or a service.
  // this might work: this.controllerFor('user').get('user.user_id');
  let user_id = this.get('user.user.user_id');

  return Ember.RSVP.hash({
    event,
    tickets: this.store.query('ticket', { user_id, event_code })
  });
},

setupController(controller, model) {
  // super sets controller model to be route model.
  // ie. controller.set('model', model);
  this._super(...arguments);

  if (!model.get('tickets.length')) {
    controller.set('noTickets', true);
  }
}