【问题标题】:Ember.js: How to apply a jquery plugin after new item is inserted to ArrayControllerEmber.js:将新项目插入 ArrayController 后如何应用 jquery 插件
【发布时间】:2013-01-09 02:31:46
【问题描述】:

所以我有一个以非常标准的方式呈现的 ArrayController:

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

我想要的是在插入新项目后应用 jQuery.timeAgo 插件,但要做到这一点,我应该以某种方式获得对插入元素的引用。

我尝试了didInsertElement 方法,但它仅在呈现整个视图时触发,我需要将此插件应用于插入到 DOM 中的每个新项目。

所以,我的问题真的可以这样表述——有没有办法获得对新插入的 DOM 元素的引用或在将新项目添加到 ArrayController 并附加到 DOM 后触发的任何回调?

【问题讨论】:

    标签: javascript ember.js


    【解决方案1】:

    我建议使用{{each}} 帮助器的无块形式来指定每个元素要使用的视图类。

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

    然后像这样定义 App.AnItemView:

    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();
      }
    });
    

    【讨论】:

    • 谢谢,它起作用了,只是对它的性能效果感兴趣,如果说,渲染大约 100 多个项目。
    【解决方案2】:

    我看到了两种可能性:

    1 - 在您的数组上设置一个观察者,每次插入元素时都会触发该观察者。但是您不会自动获得对新元素的引用。

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

    2 - 将列表项包装在自己的视图中(例如:App.ListItemView)并使用 didInsertElement 事件:

    {{#each}}
      {{#view App.ListItemView}}
        <li>... </li>
      {{/view}}
    {{/each}}
    
    App.ListItemView = Ember.View.extend({
      didInsertElement : function(){
        this.$().timeago();
      }
    }
    

    【讨论】:

    • 谢谢,#2 正是我想要的。
    猜你喜欢
    • 2012-03-27
    • 2014-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多