本文介绍了剔除afterRender,但只有一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的observableArray,其中包含许多用户模型.在标记中,有一个带有foreach循环的模板,该模板循环用户并在简单表中输出用户.我还使用自定义滚动条和其他一些JavaScript设置了表格样式.因此,现在我必须知道foreach循环何时完成并将所有模型添加到DOM中.

I have a simple observableArray which contains a lot of user-models.In the markup, there is a template with a foreach loop which loops the users and outputs them in a simple table. I additionally style the table with a custom scrollbar and some other javascript. So now I have to know when the foreach loop is finished and all the models are added to the DOM.

afterRender回调的问题是每次添加某些东西时都会调用它,但是我需要一种仅触发一次的回调.

The problem with the afterRender callback is that it gets called every time something is added, but I need kind of a callback which fires only once.

推荐答案

您最好的选择是使用自定义绑定.您可以将自定义绑定放在data-bind中的绑定列表中的foreach之后,也可以在setTimeout中执行代码,以允许foreach在执行代码之前生成内容.

Your best bet is to use a custom binding. You can either place your custom binding after foreach in the list of bindings in your data-bind or you could execute your code in a setTimeout to allow foreach to generate the content before your code is executed.

这里是一个示例,该示例一次显示运行代码,而每次observableArray更新时显示运行代码: http: //jsfiddle.net/rniemeyer/Ampng/

Here is a sample that shows running code a single time and running code each time that your observableArray updates: http://jsfiddle.net/rniemeyer/Ampng/

HTML:

<table data-bind="foreach: items, updateTableOnce: true">
    <tr>
        <td data-bind="text: id"></td>
        <td data-bind="text: name"></td>
    </tr>
</table>

<hr/>

<table data-bind="foreach: items, updateTableEachTimeItChanges: true">
    <tr>
        <td data-bind="text: id"></td>
        <td data-bind="text: name"></td>
    </tr>
</table>

<button data-bind="click: addItem">Add Item</button>

JS:

var getRandomColor = function() {
   return 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
};

ko.bindingHandlers.updateTableOnce = {
    init: function(element) {
        $(element).css("color", getRandomColor());
    }
};

//this binding currently takes advantage of the fact that all bindings in a data-bind will be triggered together, so it can use the "foreach" dependencies
ko.bindingHandlers.updateTableEachTimeItChanges = {
    update: function(element) {
        $(element).css("color", getRandomColor());
    }
};


var viewModel = {
    items: ko.observableArray([
        { id: 1, name: "one" },
        { id: 1, name: "one" },
        { id: 1, name: "one" }
    ]),
    addItem: function() {
        this.items.push({ id: 0, name: "new" });
    }
};

ko.applyBindings(viewModel);

这篇关于剔除afterRender,但只有一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 17:16