Knockout:在绑定到ViewModel函数的渲染内容中创建链接的最佳方法

Knockout: Best Way To Create Links In Rendered Content Bound To ViewModel Functions

本文关键字:创建 方法 最佳 链接 绑定 函数 ViewModel Knockout      更新时间:2023-09-26

我正在使用Knockout绑定元素:

<div data-bind="foreach: someCollection">
    <p data-bind="html: someTextProperty"></p>
</div>

然而,someTextProperty中有一些文本,我想将其转换为与ViewModel及其函数之一交互的超链接。

有没有一种简单、受支持的方法可以在动态呈现的内容呈现后对其执行绑定?foreach中的afterRender绑定(这需要大量的逻辑来确保我的目标是正确的元素)是唯一可用的吗?

编辑:

在我的真实场景中,someTextProperty看起来像这样:

This is a paragraph with some <tag data-val="foo">tagged</tag> text.

我现在正在把它转换成这样的东西:

This is a paragraph with some <a onclick="viewModel.DoSomething(''foo'')">tagged</a> text.

但是直接在链接中引用视图模型函数感觉有点脏,所以我正在寻找更好的方法。

好的,它需要一个自定义绑定处理程序来包装html绑定并将绑定应用到新代码。我刚刚做了一个神奇的计算,将原始数据转换为所需的html,并绑定计算的数据。

ko.bindingHandlers.boundHtml = {
  update: function(element, valueAccessor, allBindingsAccessor, data, context) {
    ko.bindingHandlers.html.update(element, valueAccessor, allBindingsAccessor, data, context);
    ko.utils.arrayForEach(element.children, function(node) {
      console.debug("Bind", node);
      ko.applyBindingsToNode(node, context);
    });
  }
};
data = 'This is a paragraph with some <tag data-val="foo">tagged</tag> text.';
function myTransform() {
  return 'This is a paragraph with some <a data-bind="click: DoSomething.bind(null, ''foo'')">tagged</a> text.';
}
vm = {
  someTextProperty: ko.observable(data),
  transformed: ko.computed({
    deferEvaluation: true,
    read: myTransform
  }),
  DoSomething: function(arg) {
    console.debug("Doing something with", arg);
  }
};
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="boundHtml: transformed"></div>