Ember.js - afterRender在CSS完成之前触发

Ember.js - afterRender fires before CSS is finished

本文关键字:CSS js afterRender Ember      更新时间:2023-09-26

我想在处理验证时显示加载符号。我的 .hbs 文件看起来像这样

<div {{bind-attr class='isProcessing:spinner'}}></div>

我试图将我的验证包装到 afterRender 运行循环中,但显然 afterRender 并不意味着 after-CSS。我的验证是在div 的 css 类更改之前执行的(它根本没有改变)。

App.PostController = Em.Controller.extend({
    isProcessing: false,
    actions: {
        savePost: function() {
            this.set('isProcessing', true);
            Ember.run.scheduleOnce('afterRender', this, function() {
                // do a lot of validating and other (non-asynchronous) stuff here
                // ... this may take several seconds
                this.set('isProcessing', false);
            });
        }
    }
});

在所有 CSS 渲染完成后,我的代码开始执行我该怎么办?

我也尝试了Ember.run.next。这也行不通。Ember.run.later的超时时间至少约为200毫秒,但我当然不想对任何静态时间跨度进行硬编码。

更新:这是我的问题的js小提琴:http://jsfiddle.net/4vp2mxr0/2/

任何帮助都会被理解!提前感谢!

请将您的代码包装在 Ember.run.next 中。喜欢这个:

savePost: function() {
    this.set('isProcessing', true);
    Em.run.next(this, function() {
        //just some synchronous code that takes some time (the time inbetween the two alerts)
        var i=0,a;
        alert('start code');
        while (i++ < 10000000) {
            a = Math.pow(i, Math.pow(1/i, Math.sin(i)))/3/4/5/5 * Math.log(i);
        }
        this.set('isProcessing', false);
        alert('finished code');
    }); 
}

它按预期工作。我认为您的问题是您将isProcessing设置为 true,然后立即将其设置为 false ,因为您不会等待异步代码/承诺完成。在这种情况下,您必须在解决承诺时将isProcessing设置为 false。如果这只是一个承诺,您可以isProcessing .then() 中设置false,例如:

myModel.get('children').then (children) =>
  @set 'isProcessing', false
或者,如果您解析多个承诺,

或者在循环中解析承诺,则可以使用 Ember.run.debounce,它将在最后一次调用此方法后的 XXXms 后触发,例如:

finishProcessing: ->
  @set 'isProcessing', false
actions:
  savePost: ->
    myModel.get('children').then (children) =>
      children.forEach (child) =>
        child.then (resolvedChild) =>
          Ember.run.debounce @, 'finishProcessing', 500