Billybonks
Billybonks

Reputation: 1568

Execute observer once model loaded

i am trying to have an observer execute when a model is loaded

    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('[email protected]'),

the method is currently being called twice, if i change the observes statement to

observes('blablabla'),

it also gets called twice.

the method must only execute when the attachments property of the model updates

the model code :

 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})
});

Upvotes: 1

Views: 1371

Answers (2)

Kingpin2k
Kingpin2k

Reputation: 47367

Additionally you can observe the state of the model using the current state

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

Upvotes: 1

Marcio Junior
Marcio Junior

Reputation: 19128

I think that your observer is called multiple times because for each item loaded in attachments relationship, the [email protected] is triggered. You can use Ember.run.once to collapse all these calls in a single one:

  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('[email protected]'),

I hope it helps

Upvotes: 0

Related Questions