How to Run Some JS on an Element in the Index Template in Ember.js RC2
ember.js, handlebars.js, html, javascript, jquery
Solution
I assume that you mean the template of your ApplicationView when you speak of the 'index template':
App.ApplicationView = Ember.View.extend({
didInsertElement : function(){
var that = this;
Ember.run.next(function(){
that.$('.navbar').affix({offset: -1000});
});
}
});
What are the ingredients of this solution?
- The `didInsertElement` of a View is the right place to put jQuery and jQuery plugin initialization logic.
- The `didInsertElement` hook is called when the DOM-Element of your view has been inserted, but the inner elements have not yet been inserted. Therefore i wrapped your logic in a call to `Ember.run.next()`. This call makes sure that the logic is run after your view has rendered completely, because it is run at the end of the Ember Run Loop, which is responsible for synchronizing necessary changes to the DOM.
Update: Even better solution proposed by Thomas to decrease delay between rendering and the JS Logic being run:
App.ApplicationView = Ember.View.extend({
didInsertElement : function(){
var that = this;
Ember.run.schedule('afterRender',function(){
that.$('.navbar').affix({offset: -1000});
});
}
});
Problem with the first solution according to OP:
is there any way to decrease the lag between when the element renders and when the JQuery is run, or is that simply not possible? It looks funny when elements change live after the template renders.
According to Thomas:
I've used both next and schedule to run jquery in my own app and the delay Brad mentions is significantly less to non existent with schedule
Further Reading for the ones interested in the great concept of the Ember Run Loop: http://alexmatchneer.com/blog/2013/01/12/everything-you-never-wanted-to-know-about-the-ember-run-loop/
Problem
I am writing an Ember.js application, and I would like to run the following Javascript code on a `div` with a class of `navbar` right after the view renders: ``` $('.navbar').affix({offset: -1000}); ``` I am not aware of any way to do this easily in Ember, as the standard JQuery `$(document).ready()` doesn't work with Ember apps. There has to be some easy way of doing this, but all of the other answers to this question seem to be like complex workarounds and are based on outdated versions of Ember.js. Template in Question: ``` <script type="text/x-handlebars"> <div class="navbar" data-spy="affix"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> </div> </div> </div> {{outlet}} </script> ```