1

我正在尝试从我的淘汰视图模型中的数据创建一个动态弹出框。我正在编写一个自定义绑定处理程序,它为数组中的每个项目加载一个模板。

这是我的绑定处理程序的开始。

ko.bindingHandlers.notificationsPopover = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        console.log('init called');
    },

    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        console.log('update called');
        console.log(value);

        var notifications = $("<div>");

        $.each(value, function () {
            console.log(ko.toJS(this));
            var data = this;
            var elm = $("<div>");

            ko.renderTemplate('Notification', data, {
                afterRender: function (nodes) {
                    notifications.append(elm.html());
                    console.log("Called");
                }
            }, elm.get(0), "replaceChildren");
        });

        var options = {
            title: 'Notifications',
            html: true,
            content: "'" + notifications.html() + "'",            
            placement: 'bottom'
        };
        $(element).popover(options);
        console.log(notifications.html());
    }
};

在控制台中,我看到更新被调用了两次。一次没有数据,第二次将数据加载到该元素绑定的数组中。虽然我的 afterRender 只被调用一次,但当时的 notification.html() 包含:

<div class="infuser-loading">Loading...</div> 

我的模板如下所示:

<div class="row-fluid">
    <div class="span3">
        <img data-bind="attr: { src: senderphoto(), alt: sendername() }" />
    </div>
    <div class="span9">
        <p data-bind="html: message()"></p>
    </div>
</div>

我怎样才能让它为数组中的每个项目加载模板,然后将这些模板连接在一起作为弹出框的内容?

4

0 回答 0