当ember完成DOM更新时做一些事情

时间:2012-05-21 13:58:06

标签: javascript ember.js

我希望在ember绑定已经同步并且DOM再次更新时做一些事情。

我尝试使用操作绑定模型的函数的回调,在执行回调时不更新DOM。

我已经在模型上直接尝试了观察者,在执行观察者时不会更新DOM。

我已尝试使用绑定的观察者,在执行观察者时不会更新DOM。

e.g。

App.view = Ember.View.extend({
    modelBinding: 'App.model',
    modelChanged : function() {
        window.scrollTo(0, document.body.scrollHeight);
    }.observes('model'),

    getMore: function(event) {
        App.set('model', "somethingnew");
    }
});

当我触发" gotMore"时,我更新模型,当模型更新并且其更改已经呈现时,我想向下滚动。

在我尝试的任何方式中,我都能够获得新的scrollHeight。在这些事件发生后几毫秒设置。

以下是jsFiddle的一个例子: http://jsfiddle.net/kcjzw/15/

2 个答案:

答案 0 :(得分:7)

此处记录了执行此操作的正确方法:

http://emberjs.com/api/classes/Ember.run.html#method_next

modelChanged : function() {
  Ember.run.scheduleOnce('afterRender', this, function() {
    window.scrollTo(0, document.body.scrollHeight);
    $('body').append('New scroll height: '+document.body.scrollHeight);
  });
}.observes('content')

答案 1 :(得分:2)

使用Ember.run.next

https://github.com/emberjs/ember.js/blob/master/packages/ember-metal/lib/run_loop.js#L531-566

App.view = Ember.View.extend({
    modelBinding: 'App.model',
    modelChanged : function() {
        Ember.run.next(myContext, function(){
            // code to be executed in the next RunLoop, which will be scheduled after the current one
            window.scrollTo(0, document.body.scrollHeight);
        });
    }.observes('model'),

    getMore: function(event) {
        App.set('model', "somethingnew");
    }
});

<强>更新

看看这个:http://jsfiddle.net/ud3323/hZ7Vx/

您需要的是在runloop之后运行代码,该代码会呈现Ember.CollectionView帮助程序将创建的{{each}}

的JavaScript

App = Ember.Application.create();

App.model = Ember.Object.create({
    items: [1]
});

App.view = Ember.Handlebars.EachView.extend({
    contentBinding: 'App.model.items',

    itemViewClass: Ember._MetamorphView.extend({
        templateName: 'the_template'
    }),

    modelChanged : function() {
        Ember.run.next(this, function(){
            window.scrollTo(0, document.body.scrollHeight);
            $('body').append('New scroll height: '+document.body.scrollHeight);
        });
    }.observes('content'),

    theAction: function(event) {
        App.controller.doStuffToModel();
    }
});

App.controller = Ember.Object.create({
    doStuffToModel : function() {
        App.model.set('items', [1,2,3,4,5]);
    }
});

车把

<script type="text/x-handlebars" data-template-name="the_template">
    <div style="height:200px;"></div> 
</script>

<script type="text/x-handlebars">
    {{view App.view}}
</script>​