我是Knockout的新手,我正在尝试使用一个jquery插件,它将自定义样式应用于某些元素。但是因为我有一个页面从ajax调用中获取内容并且所有元素都是通过敲除构建的,所以初始jquery函数调用不知道页面上有任何元素,因此不对这些元素应用样式
所以我要问的是,在敲除操作元素(DOM)之后如何回调jquery函数?
现在我正在调用jquery函数如下: -
$(document).on("load",function(){
$(".element").callPlugin("add-style");
});
答案 0 :(得分:7)
applyBindings
是同步的,因此您可以在callPlugin
之后致电ko.applyBindings(VM)
(在下一行)。
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>
请注意updateUI
中的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进行任何更改时自动初始化和更新。
希望这有帮助!
答案 1 :(得分:0)
我建议通过自定义绑定执行此操作: 这样,您的“外部代码”就可以与数据绑定更加集成。如有必要,您还将获得更新支持。
在此处阅读有关此概念的更多信息 http://knockoutjs.com/documentation/custom-bindings.html