javascript - foreach 完成渲染时的自定义绑定(bind)

标签 javascript knockout.js knockout-2.0

我有一个可观察数组,其中的项目绑定(bind)到 ul。添加项目后,我需要计算整个 li 项目集的宽度,以便我可以将 ul 元素的宽度设置为子元素的总宽度li 元素。

如何使用 foreach 绑定(bind)来执行此操作?

<div>
    <h2 data-bind="visible: items().length">Test</h2>
    <ul data-bind="foreach: { data: items, afterAdd: $root.myAfterAdd }">
        <li data-bind="text: name"></li>
    </ul>
</div>

和 JavaScript:

var viewModel = {
    items: ko.observableArray([
        { name: "one" },
        { name: "two" },
        { name: "three" }
        ]),
    myAfterAdd: function(element) {
        if (element.nodeType === 1) {
           alert("myAfterAdd");   
        }
    },
    addItem: function() {
        this.items.push({ name: 'new' });
    }
};


ko.applyBindings(viewModel);

// once foreach has finished rendering I have to set the width 
// of the ul to be the total width of the children!

我尝试使用 afterAdd 这样我就可以在添加每个元素后“更新”ul 的宽度,不幸的是我发现 afterAdd > 初始元素不会触发!它只会在推送其他项目时触发...

请注意,li 项中的内容宽度未知:)

参见this fiddle示例场景。

最佳答案

我也遇到了类似的问题。您可以使用它来进行初始计算:

ko.bindingHandlers.mybinding {
        init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
            var foreach = allBindings().foreach,
                subscription = foreach.subscribe(function (newValue) {
                // do something here (e.g. calculate width/height, use element and its children)
                subscription.dispose(); // dispose it if you want this to happen exactly once and never again.
            });
        }
}

关于javascript - foreach 完成渲染时的自定义绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16592237/

相关文章:

knockout.js - 在按键和点击事件上更新可观察的

javascript - 打开和关闭网站上的声音

javascript - 导航链接上的 jQuery 事件类没有改变

javascript - 正确构建knockoutjs View 模型和服务器调用

javascript - KnockoutJS 与 Sammy.js SPA 建议

javascript - 分页不适用于 KO Grid

javascript - 使用矩以编程方式设置 ionic /Angular 日期输入

javascript setInterval 函数对我不起作用

c# - knockout 绑定(bind)第二次不起作用

knockout.js - 使用 knockout.js ,我的模板中需要一个 'count'