Schedule for every afterRender for a View

646 Views Asked by At

I would like to run code every time a view is rendered. The closest I can get is to listen to every property that could change and explicitly schedule something on the run loop for afterRender, but I would love to just have a lifecycle hook like afterRender. The property approach gets fragile, since you have to keep the list of properties up to date based on what can affect the render.

Controller:

App.IndexController = Ember.Controller.extend({
  count: 0,
  actions: {
    add: function() {
      var count = this.get('count');
      count += 1;
      this.set('count', count);
    }
  }
});

View:

App.IndexView = Ember.View.extend({
  changed: function() {
    Ember.run.scheduleOnce('afterRender', this.after);
  }.observes('controller.count'),
  after: function() {
    console.log('after render', this.$('span').text());
  }
});

Template:

<button {{action "add"}}>add</button> <span>{{count}}</span>

http://emberjs.jsbin.com/wujogejeso/3/edit?html,css,js,output

1

There are 1 best solutions below

1
On

To schedule the code afterRender, you can use the didInsertElement lifecycle hook in place of your changed function.

App.IndexView = Ember.View.extend({
  didInsertElement: function() {
    Ember.run.scheduleOnce('afterRender', this.after);
  },
  after: function() {
    console.log('after render', this.$('span').text());
  }
});