2

Is it possible to trap a global event in Ember when a template is rendered?

This is so I can invoke initialisation scripts on a per template basis as described. This isn't a candidate for initializers - I'm trying to initialise some jQuery plugins on approx 30% of pages in my application, so doing this once and not repeating myself would be great.

Failing a global hook, what is the most appropriate location to hook a template being rendered? I'm only using templates so I can't trap didInsertElement on a View.

Sam
  • 4,219
  • 7
  • 52
  • 80

1 Answers1

2

I don't know if it's the proper way but i gave it a try as your question interested me. The follow seems to work : http://emberjs.jsbin.com/pujiqipafe/1/edit?html,js,output

Basically i use the route hook renderTemplateand add :

Ember.run.scheduleOnce('afterRender', myfunction);

after calling the this.render().

You can extend this by making a

App.MyJqueryRoute = Ember.Route.Extend({
  renderTemplate: function(){
    this.render();
    var myjquery = function(){
      //do your jQuery stuff here
    };
    Ember.run.scheduleOnce('afterRender', myjquery);
  }
});

Then simply extend App.MyJqueryRouteinstead of Ember.Route.Extend in the routes you need this functionality.

(This is a proposal idea i had while reading your post, i'm not an ember expert so i would be happy to hear any other solutions or improvement of my solutions from the community)

Ryan
  • 39
  • 1
  • 6
MrVinz
  • 874
  • 6
  • 15
  • Why not just reopen the Route class and override renderTemplate? It will work with all the routes. http://emberjs.jsbin.com/miluhecupi/1/edit – blessanm86 Jan 12 '15 at 14:16
  • @blessenm cause he said on 30% of his pages, so with a reopen it would execute useless code on 70% of the pages. – MrVinz Jan 12 '15 at 14:21
  • Ah I didn't read the question thoroughly. Yes ur point is valid. Ur answer seems to be the way to go. – blessanm86 Jan 12 '15 at 14:26
  • @blessenm i hope so but it would be great to have an answer from the author – MrVinz Jan 12 '15 at 14:31
  • Another way which I think is proper is to wrap the jquery plugins in a component and initialize them in the didInsertElement hook. This will also allow us to use the component lifecycle to do the cleanup of the plugin. – blessanm86 Jan 12 '15 at 14:42