EmberJS在渲染所有视图后执行JS

时间:2013-06-28 21:57:41

标签: jquery view ember.js render

我正在尝试运行此代码:

var width = 0; 
$('.photos article').each(function(){ width = width + $(this).width();});
$('.photos').width(width);

在视图呈现后无法弄清楚如何做到这一点,这里是包含所有视图和内容的代码:

http://jsbin.com/okezum/6/edit

我想在所有视图上运行我的代码,有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

您可以通过在所有视图上定义didInsertElement挂钩来实现您要做的事情,并且在获取DOM元素的id之后,您可以执行您可能需要的任何jQuery代码。由于您希望在“全部”视图上执行此操作,因此您可以编写一个通用视图,从中可以扩展所有需要执行代码的视图。

示例:

App.GeneralView = Ember.View.extend({
  didInsertElement: function() {
    var width = 0; 
    $('.photos article').each(function(){ 
      width = width + $(this).width();
    });
    $('.photos').width(width);
  }
});

App.IndexView = App.GeneralView.extend();
...

请注意,如果需要获取视图的ID,您可以使用this.get('elementId')访问它,我还修改了您的jsbin,请参阅here了解工作版本。

希望它有所帮助。

答案 1 :(得分:0)

修正了这个问题:

App.GeneralView = Ember.View.extend({
    didInsertElement: function() {
        if (this.$().find(".post img").length > 0) {
            var WIDTH = 0, HEIGHT = $(window).height(), SIDEBAR_WIDTH =   $('#sidebar').outerWidth();
            this.$().find(".post").each(function(){
                WIDTH += parseInt($(this).find('img').attr('width'));
                $(this).find('img').height(HEIGHT - 80).removeAttr('width');
            });
            $('body').children('.ember-view').innerWidth(WIDTH);
        } else {
            Ember.run.next(this, function() {
                this.didInsertElement();
            });
        }
    }
});

不知道这是最好的方法,但是有效; s