模型加载后执行观察者

时间:2013-11-18 17:19:13

标签: ember.js ember-data

我正在尝试在加载模型时执行观察者

    sortAttachments:function(){
     console.log('sorting')
     var attachments = this.get('model').get('attachments');
     for(var i = 0;i<attachments.length;i++){
       var a = attachments[i];
       if(a.type=="Link"){
         links.push(a)
       }
     }
   }.observes('models.attachments.@each.type'),

如果我将observes语句更改为

,则该方法当前被调用两次
observes('blablabla'),

它也会被调用两次。

该方法必须仅在模型的附件属性更新时执行

型号代码:

 App.Card = DS.Model.extend({
  title: DS.attr('string'),
  description: DS.attr('string'),
  left: DS.attr('number'),
  top: DS.attr('number'),
  user: DS.belongsTo('user', { async: true }),
  attachments: DS.hasMany('attachment',{async:true}),
  tags:DS.hasMany('tag',{async:true})
});

2 个答案:

答案 0 :(得分:1)

此外,您可以使用当前状态

观察模型的状态
App.ApplicationController = Em.ObjectController.extend({
  timesFired: 0,

  watcher: function(){
    if(this.get('model.currentState.stateName') == 'root.loaded.saved'){
      this.incrementProperty('timesFired');
    }
  }.observes('model.currentState.stateName')
});

http://jsbin.com/aYIkAcUk/9/edit

答案 1 :(得分:0)

我认为您的观察者被多次调用,因为对于attachments关系中加载的每个项目,model.attachments.@each.type都会被触发。您可以使用Ember.run.once将所有这些调用合并为一个:

  sortAttachments:function(){
     console.log('sorting')
     var attachments = this.get('model').get('attachments');
     for(var i = 0;i<attachments.length;i++){
       var a = attachments[i];
       if(a.type=="Link"){
         links.push(a)
       }
     }
  },
  sortAttachmentsOnce: function() {
    Ember.run.once(this, this.sortAttachments);
  }.observes('model.attachments.@each.type'),

我希望它有所帮助