Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember.js: How to apply a jquery plugin after new item is inserted to ArrayController

So I have an ArrayController which is rendered in pretty standard way:

<ul>
  {{#each controller}}
     <li>{{ user.name }} : {{message}} <abbr class="timeago" title="{{unbound datetimeFormatted}}">{{unbound datetimeFormatted}}</abbr></li>
  {{/each}}
</ul>

What I want is to apply a jQuery.timeAgo plugin after new item have been inserted, but to do this I somehow should get a reference to the inserted element.

I tried didInsertElement method but it fires only when the whole view is rendered, and I need to apply this plugin to each new item inserted into DOM.

So, my question really could be formulated something like this - is there any way to get a reference to newly inserted DOM element or any callback that fires after a new item have been added to ArrayController and appended to the DOM?

like image 421
Alexander Petrovich Avatar asked Jan 08 '13 17:01

Alexander Petrovich


2 Answers

I would recommend using the blockless form of the {{each}} helper to specify a view class to be used by each element.

<ul>{{each controller itemViewClass="App.AnItemView"}}</ul>

Then define App.AnItemView like this:

App.AnItemView = Ember.View.extend({
  template: Ember.Handlebars.compile('{{ user.name }} : {{message}} <abbr class="timeago" title="{{unbound datetimeFormatted}}">{{unbound datetimeFormatted}}</abbr>'),
  didInsertElement : function(){
    this.$().timeago();
  }
});
like image 168
Mike Grassotti Avatar answered Oct 09 '22 04:10

Mike Grassotti


I see 2 possibilities:

1 - Setup an observer on your array, which gets fired every time an element is inserted. But you do not get a reference to the new element automatically.

yourObserver : function(){
    ...
}.observes("content.@each")

2 - Wrap your list items in an own view (e.g.: App.ListItemView) and use the didInsertElement event:

{{#each}}
  {{#view App.ListItemView}}
    <li>... </li>
  {{/view}}
{{/each}}

App.ListItemView = Ember.View.extend({
  didInsertElement : function(){
    this.$().timeago();
  }
}
like image 43
mavilein Avatar answered Oct 09 '22 04:10

mavilein