且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Knockout.js模板中使用jQuery?

更新时间:2023-11-30 22:41:28

文件在 ko.applyBindings 完成之前已经准备好了,所以这就是为什么你看不到元素。但是,您不应该使用jQuery来违反视图模型和DOM之间的边界。在淘汰赛中,完成所需要的方式是自定义绑定

It's true that the document is ready before ko.applyBindings finishes, so that's why you're not seeing the element. However, you should not be using jQuery to violate the boundary between your view model and the DOM like that. In knockout, the way to accomplish what you need is with custom bindings.

基本上,您定义一个新的敲除绑定(如文本,值,foreach等),并且您可以访问 init 函数,该函数在元素被首先渲染,并且$ code>更新函数,当您传递给绑定的值被更新时触发。在您的情况下,您只需要定义 init

Basically, you define a new knockout binding (like text, value, foreach, etc) and you have access to an init function, which fires when the element is first rendered, and an update function, which fires when the value you pass to the binding is updated. In your case, you would only need to define init:

ko.bindingHandlers.customVideo = {
    init: function (element) {
        console.log(element, $(element));  // notice you can use jquery here
    }
};

然后你使用这样的绑定:

And then you use the binding like this:

<div data-bind="customVideo"></div>

也许***在init回调中添加视频类并执行其他初始化: / p>

Perhaps it's better to add the "video" class and do other initialization right in the init callback:

ko.bindingHandlers.customVideo = {
    init: function (element) {
        $(element).addClass('video');
    }
};

如果这首先感觉有点笨,记住有一个非常好的间接原因。它使您的视图模型与其适用的DOM分离。因此,您可以更***地更改DOM,您可以更独立地测试视图模型。如果您等待 ko.applyBindings 完成并调用了一些jQuery的东西,那么您将更难测试该代码。请注意,敲除自定义绑定以任何方式不是特殊,您可以看到内置绑定的定义完全相同: https://github.com/knockout/knockout/tree/master/src/binding/defaultBindings

If this feels a little wonky at first, remember there's a very good reason for the indirection. It keeps your view model separate from the DOM it applies to. So you can change the DOM more freely and you can test the view model more independently. If you waited for ko.applyBindings to finish and called some jQuery stuff after that, you'd have a harder time testing that code. Notice that knockout custom bindings are not "special" in any way, and you can see that the built in bindings are defined exactly the same: https://github.com/knockout/knockout/tree/master/src/binding/defaultBindings