tspore
tspore

Reputation: 1349

Adding Custom Scripts to Ember

So on my app, as it is loading in a table from the rails DB side, it comes in very late, and my little $('tr:even').addClass("trAlt"); - only reads 1 tr, and doesn't apply the css class for styling. I have placed the script on didInsertElement as follows:

App.RecordsView = Ember.View.extend({
    templateName: 'records/index',
    contextBinding: 'App.RecordController',
    didInsertElement: function(){
         $('tr:even').addClass("trAlt")
    }
});

But the inital load is 1 tr row (the headings), and then Ember isn't firing off the even as the view changes. Most of the code is the same as from this question.

Upvotes: 1

Views: 376

Answers (3)

Mike Grassotti
Mike Grassotti

Reputation: 19050

Consider using the blockless form of {{each}} and move the jQuery code to didInsertElement of each row as follows:

App.RecordsView = Ember.View.extend({
    templateName: 'records/index',
    contextBinding: 'App.RecordController'
});

App.RecordRowView = Ember.View.extend({
    templateName: 'records/record',
    tagName: 'tr',
    didInsertElement: function(){
      $('tr:even').addClass("trAlt")
    }
});

// in records/index.hbs
{{each controller itemViewClass="App.RecordRowView"}} 

http://emberjs.com/api/classes/Ember.Handlebars.helpers.html#method_each

Upvotes: 2

Shimon Rachlenko
Shimon Rachlenko

Reputation: 5517

You can observe the isLoaded property of controller's content:

App.RecordsView = Ember.View.extend({
    templateName: 'records/index',
    contextBinding: 'App.RecordController',

    onRecordsLoaded: function () {
        $('tr:even').addClass("trAlt");
    }.observes('App.RecordController.content.isLoaded')
});

Upvotes: 0

CraigTeegarden
CraigTeegarden

Reputation: 8251

Can you use plain CSS to automatically style the table? This will apply to the rows even if they are added after didInsertElement() is called.

CSS:

tr:nth-of-type(even) {
  background-color:red;
}

JSBin example

Upvotes: 0

Related Questions