Knockout.js - “html”绑定中的“值”绑定

Thr*_*mon 2 html javascript data-binding knockout.js

我正在开发一个需要根据某些值动态生成 HTML 的应用程序。我有以下代码,我希望动态 HTML 在其中运行:

<div data-bind="html: extraHTML"></div>
Run Code Online (Sandbox Code Playgroud)

我在我的 javascript 文件中有一个对象设置,其中包含各种 HTML 代码块,一旦应用程序启动,就会选择这些代码块。例如,对象之一包含以下内容:

{ type: 'Int', html: '<input style=\'margin: 0\'type=\'number\' min=\'0\' data-bind=\'value: selectedExtra, valueUpdate: \'input\'\' />' }
Run Code Online (Sandbox Code Playgroud)

当我运行应用程序时,我没有收到任何错误并且 HTML 被正确绑定,但是当我在输入字段中插入一个值时,可观察的“selectedExtra”不会更新。当我用以下内容替换包含“html”绑定的 div 标签时:

<input style="margin: 0" type="number" min="0" data-bind="value: selectedExtra, valueUpdate: 'input'">
Run Code Online (Sandbox Code Playgroud)

可观察更新就可以很好地做到这一点。我想知道的是,是否可以在“html”绑定中动态分配“值”绑定并实际更新该值。也许我错过了另一个解决方案?

任何帮助将不胜感激,谢谢!

更新

我创建了一个 jsfiddle 来演示这里的问题。

小智 5

当您调用 applyBindings 时,ko 会遍历 dom 节点以“绑定”到元素。您的 html 已生成,因此永远不会为这些元素调用 ko.applyBindings。

您有 2 个选择: - 使用 Wayne 评论的模板,(推荐) - 如果您真的想从 observable 生成 html 并绑定 ViewModel,您可以使用自定义绑定。您实际上是在此处创建一些自定义模板系统。

html:

<div data-bind="htmlTemplate:html"></div>
Run Code Online (Sandbox Code Playgroud)

绑定处理程序:

ko.bindingHandlers.htmlTemplate = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
       // NOTE: you could return false and ommit the update code, it probably works, but this way you have more control what happens when the html is updated
       return { controlsDescendantBindings:true };
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // remove old bindings
        ko.cleanNode(element);

        // update the inner html, unrwap to support observables and/or normal properties            
        element.innerHTML=ko.unwrap(valueAccessor());

        // apply the view model to the content of the element
        ko.applyBindingsToDescendants(viewModel,element);
    }
};
Run Code Online (Sandbox Code Playgroud)

JSFIDDLE:http : //jsfiddle.net/martijn/6b87vw3L/