applyBindings
是同步的,所以你可以ko.applyBindings(VM)
後調用callPlugin
(下一行)。
ko.applyBindings(VM);
$(".element").callPlugin("add-style");
或者,如果您多次更新UI,則可以使用custom bindings。假設.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>
注意在data-bind
的updateUI
。這是對應的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自動更新。
希望這有助於!
將此標記爲正確的,因爲這是用很好的示例解釋的。我沒有使用自定義綁定,它的工作。謝謝。自兩天以來我一直在努力尋找解決方案。我很喜歡Knockout。 – shriek
值得一提的是,當您使用'ko.options.deferUpdates = true;'時,'ko.applyBindings()'的繪畫是不同步的。因此,例如,如果您嘗試直接獲取'svg.getCTM()',它將不會按照建議工作。 – kernel