0

我对 Knockout 相当陌生,我正在尝试使用一个 jquery 插件,它将自定义样式应用于某些元素。但是由于我有一个从 ajax 调用获取内容的页面,并且所有元素都是通过淘汰赛即时构建的,所以初始 jquery 函数调用不知道页面上有任何元素,因此没有对这些元素应用样式.

所以我要问的是如何在敲除操作元素(DOM)后回调一个 jquery 函数?

现在我正在调用 jquery 函数如下: -

$(document).on("load",function(){
    $(".element").callPlugin("add-style");
});
4

2 回答 2

7

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>

注意updateUIin 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 进行任何更改时自动初始化和更新。

希望这可以帮助!

于 2013-07-06T17:01:43.743 回答
0

我建议通过自定义绑定来执行此操作:这样您的“外部代码”可以与您的数据绑定更加集成。如有必要,您还将获得更新支持。

在此处阅读有关此概念的更多信息 http://knockoutjs.com/documentation/custom-bindings.html

于 2013-07-06T17:01:26.763 回答