knockout - execute code after the last item has been rendered

我的未来我决定 提交于 2019-12-04 05:31:36

The foreach binding afterRender option can do what you are looking for, the trick part is to be able to know that the element is the last one. That can be solved using the provided arguments like shown in http://jsfiddle.net/n54Xd/.

The function:

this.myPostProcessingLogic = function(elements, data) {
    if(this.foreach[this.foreach.length-1] === data)
        console.log("list is rendered");
};

Will be called for every element but the "if" will make sure the code only runs for the last element.

Try to subscribe manually on the array changes. By using subscribe you will be notified on array modification.

If you subscribe after applyBindings call, you will be notified after the refresh process of the view.

See fiddle

var ViewModel = function () {
    var self = this;

    self.list = ko.observableArray();

    self.add = function () {
        self.list.push('Item');
    }
    self.list.subscribe(function () {
        alert('before');
    });
};
var vm = new ViewModel();
ko.applyBindings(vm);

vm.list.subscribe(function () {
    alert('after');
});

I hope it helps.

I was successful using Ricardo Medeiros Penna's answer with just one little tweak.

    this.myPostProcessingLogic = function(elements, data) {
      if(this.foreach._latestValue[this.foreach._latestValue.length-1] === data)
        console.log("list is rendered");
    };

I had to add _latestValue to get the length value and now it is working as desired.

Use throttle extender, this way computed will be called once after you finished populating the array:

  self.counter = ko.computed(function () {
        return self.containers().length;
    }).extend({ throttle: 100 });

Late addendum, but the if statement in Ricardo's answer above should be:

if (this.foreach()[this.foreach().length - 1] === data) {
    //Your post processing logic
}

as foreach is a function. Most likely why Nir weiner has an issue with it evaluating.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!