有没有办法在 knockoutjs 渲染后只知道绑定上下文来 运行 编码?

Is there a way to run code after knockoutjs render only knowing the binding context?

我正在 CMS 后端开发一个模块。我正在尝试 'hook in' 他们的敲除绑定和 运行 代码,当他们完成渲染时。到目前为止我没有运气。

然而,我已经附加到不同的数据组件并获得了敲除数据。

我有很多失败的尝试,但到目前为止,我有这个正在返回绑定上下文。

var bindingContext = ko.contextFor(jQuery('div[data-component="customer_form.areas"]').get(0));

有谁知道我可以使用它以某种方式附加一个观察者来观察渲染完成的方法吗?我会管理,我是淘汰赛的新手。我没有创建视图模型,也没有创建模板。我无法像我认为的那样将 afterRender 添加到模板 should

正如您所说,应该 使用 afterRender 完成。所有其他方法都感觉很老套,因为你永远不知道什么时候 knockout 会重新渲染 ui.

的(部分)

我想不出为什么你需要这样的解决方法,但我能判断谁..

我能想到的唯一方法是使用 MutationObserver。这是一个例子:

var bindingContextElement = document.querySelector("ul");

var renderThrottle = 300;
var renderCycle = null;
var onRenderComplete = function() {
  var pre = document.createElement("pre");
  var msg = new Date().toLocaleString() + ": finished rendering";
  pre.appendChild(document.createTextNode(msg));
  document.body.appendChild(pre);
}

// Observe mutations to element, call onRenderComplete after 300ms of no mutations
var observer = new MutationObserver(function(mutations) {
  clearTimeout(renderCycle);
  renderCycle = setTimeout(onRenderComplete, renderThrottle);
});

var config = {
  childList: true
};

observer.observe(bindingContextElement, config);

ko.applyBindings({
  items: ko.observableArray([1, 2, 3])
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<ul data-bind="foreach: items">
  <li data-bind="text: $data"></li>
</ul>

<button data-bind="click: function() { items.push(items().length + 1)}">add</button>

此代码侦听 <ul> 元素中的任何突变,该元素由敲除控制。一旦元素或其子元素开始发生更改,它就会尝试记录 "Rendered" 消息。只有在 300 毫秒内没有进一步变化时才允许记录此消息。

查看 the docs 以确定您的 config 对象和要观察的元素...请记住,如果事情变得比这更复杂,事情可能会失控例如...