Knockoutjs将模型绑定到使用ko.renderTemplate创建的模板

And*_*ist 5 knockout.js

我要做的是创建一个DOM节点,使用ko.renderTemplate渲染模板覆盖创建的节点,然后在该模板中都能够从特定模型和viewModel $ root获取数据.

例如:

var data = new ModelData();
var domNode = document.createElement("div");
document.body.appendChild(domNode);
ko.renderTemplate('template', data, {}, domNode, 'replaceNode');
Run Code Online (Sandbox Code Playgroud)

模板看起来像:

<script type="text/html" id="template">
    <span data-bind="text: DataFromModel"></span>
    <ul data-bind="foreach: $root.DataFromViewModelRoot">
    </ul>
</script>
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我没有从$ root.DataFromViewModelRoot获取任何数据,因为它认为$ root-data是ModelData(我理解为什么,我只是不知道应该怎么做).

我想要完成的是我需要从模板创建一个模态窗口(bootstrap),然后我希望能够根据我发送到它的数据显示该模态中的不同内容".我还需要能够创建多个模态,这就是我需要创建一个新DOM节点的原因.

RP *_*yer 5

这与您的具体问题略有不同,但这是使用引导模式的另一种方法.

您可以使用包装引导程序modaltemplate绑定的自定义绑定.

绑定可能如下所示:

ko.bindingHandlers.modal = {
    init: function(element, valueAccessor, allBindings, vm, context) {
        var modal = valueAccessor();
        //init the modal and make sure that we clear the observable no matter how the modal is closed
        $(element).modal({ show: false, backdrop: 'static' }).on("hidden.bs.modal", function() {
            if (ko.isWriteableObservable(modal)) {
                modal(null);
            }
        });

        //template's name field can accept a function to return the name dynamically
        var templateName = function() {
            var value = modal();
            return value && value.name;
        };

        //a computed to wrap the current modal data
        var templateData = ko.computed(function() {
            var value = modal();
            return value && value.data;
        });

        //apply the template binding to this element
        ko.applyBindingsToNode(element, { template: { 'if': modal, name: templateName, data: templateData } }, context);

        //tell KO that we will handle binding the children (via the template binding)
        return { controlsDescendantBindings: true };
    },
    update: function(element, valueAccessor) {
        var data = ko.utils.unwrapObservable(valueAccessor());
        //show or hide the modal depending on whether the associated data is populated
        $(element).modal(data ? "show" : "hide");
    }
};
Run Code Online (Sandbox Code Playgroud)

现在,您将在页面上绑定单个模态,如:

<div class="modal hide fade" data-bind="modal: currentModal"></div>
Run Code Online (Sandbox Code Playgroud)

currentModal将是一个可观察的,你用一个包含name(模板名称)和的对象填充data.

这种方法的工作方式是,如果currentModal填充,则使用当前模板和数据显示模态.如果currentModal为null,则关闭模态.

这是一个如何工作的示例:http://jsfiddle.net/rniemeyer/NJtu7/