【问题标题】:EmberJS Execute JS after Render on all ViewsEmberJS 在所有视图上渲染后执行 JS
【发布时间】:2013-06-26 19:01:01
【问题描述】:

我正在尝试运行此代码:

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

视图渲染后不知道怎么做,下面是包含所有视图和内容的代码:

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

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

【问题讨论】:

    标签: jquery view ember.js render


    【解决方案1】:

    已修复:

    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

    【讨论】:

      【解决方案2】:

      您可以通过在所有视图上定义 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 以获得工作版本。

      希望对你有帮助。

      【讨论】:

      • 我明白了,这很有意义 :D 但你知道为什么 width 会返回 0 吗? :s
      • 只要放一个控制台日志,它就会返回有效宽度:jsbin.com/ezunic/3/edit
      • 嗯,我在应用您的代码时来到这里,孩子的宽度求和并获得我无法获得的总宽度,它返回 []。我正在尝试获取 article 宽度,从那时到总和:s 知道吗?
      • 会不会是$(.photos article) 不符合您的需求?看看你的模板,应该不是$(section article)
      • 我还编辑了我的答案,因为我没有意识到您想要循环的实际元素而不是孔视图。
      猜你喜欢
      • 2012-08-23
      • 2012-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-25
      • 2021-12-15
      相关资源
      最近更新 更多