Skip to content Skip to sidebar Skip to footer

How To Run Some Js On An Element In The Index Template In Ember.js Rc2

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

Solution 1:

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?

  1. The didInsertElement of a View is the right place to put jQuery and jQuery plugin initialization logic.
  2. 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/

Solution 2:

My assumptions:

  • That code is the only thing in your HTML page (along with your JavaScript includes).
  • This is the only code in your JavaScript file:

    App = Ember.Application.create();

If those two assumptions are correct then you're not working with the index template, you're actually working with the application template. Every view has an init function. The simplest thing for you to do is override that function like so:

App.ApplicationView = Ember.View.extend({
    init: function(){
        this._super();
        alert('do something here');
    }
});

Here's a Fiddle for you to review.

Post a Comment for "How To Run Some Js On An Element In The Index Template In Ember.js Rc2"