淘汰后渲染,但只有一次 [英] Knockout afterRender, but just once

查看:21
本文介绍了淘汰后渲染,但只有一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 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.

推荐答案

最好的办法是使用自定义绑定.您可以将您的自定义绑定放在 foreach 之后的 data-bind 绑定列表中,或者您可以在 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);

这篇关于淘汰后渲染,但只有一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆