applyBindings
是同步的,所以你可以callPlugin
在之后调用ko.applyBindings(VM)
(在下一行)。
ko.applyBindings(VM);
$(".element").callPlugin("add-style");
或者,如果您要多次更新 UI ,则可以使用自定义绑定。假设.element
是一个<div>
(也可以是其他任何东西),您的标签将如下所示:
<div class="element" data-bind="text: 'This is just some text which KO will bind',
updateUI: true">
This text will change. Wait for it..
</div>
注意updateUI
in data-bind
。这是它对应的JS代码:
ko.bindingHandlers.updateUI = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext){
// This will be called when the binding is first applied to an element
// Set up any initial state, event handlers, etc. here
$(".element").callPlugin("add-style");
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
// This will be called once when the binding is first applied to an element,
// and again whenever the associated observable changes value.
// Update the DOM element based on the supplied values here.
$(".element").callPlugin("update-style"); // just saying
}
};
这将使您的插件在对 DOM 进行任何更改时自动初始化和更新。
希望这可以帮助!