KnockoutJS:调用不带参数的 applyBindings 有什么作用?

KnockoutJS: What Does Calling applyBindings Without Arguments do?

我正在处理一些我没有编写的有趣的代码,并且遇到了一个 RequireJS 模块,它似乎为应用程序初始化了一个 KnockoutJS 实例。

define([
    'ko',
    './template/engine',
    'knockoutjs/knockout-repeat',
    'knockoutjs/knockout-fast-foreach',
    'knockoutjs/knockout-es5',
    './bind/scope',
    './bind/staticChecked',
    './bind/datepicker',
    './bind/outer_click',
    './bind/keyboard',
    './bind/optgroup',
    './bind/fadeVisible',
    './bind/mage-init',
    './bind/after-render',
    './bind/i18n',
    './bind/collapsible',
    './bind/autoselect',
    './extender/observable_array',
    './extender/bound-nodes'
], function (ko, templateEngine) {
    'use strict';

    ko.setTemplateEngine(templateEngine);
    ko.applyBindings();
});

此代码调用 ko.applyBindings() 没有 视图模型。我对 knockout 很陌生,但是 all 我看过的教程表明您需要传递 applyBindings 一个 viewModel 对象。

不带参数调用 applyBindings 到底有什么作用?

我的最终目标是弄清楚这个应用程序(Magento 2,如果有人好奇的话)是如何使用 Knockout 来渲染东西的,所以我正在寻找 Knockout 开发人员可能会做这样的事情的原因。

如果没有 viewmodel,knockout 的大部分功能将毫无意义,但这并不是必需的。您可以在 the source 中看到,当您不传递 viewmodel 参数时没有任何问题:它只是将绑定上下文设置为 undefined:

function getBindingContext(viewModelOrBindingContext) {
    return viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
        ? viewModelOrBindingContext
        : new ko.bindingContext(viewModelOrBindingContext);
}

几个例子我能想到为什么没有视图模型 applyBindings

  • 注入静态模板
  • 附加全局上下文中的事件侦听器方法

我必须承认,虽然这些感觉有点做作...我实际上不知道为什么您显示的代码会这样做...

window.logClick = function(data, event) {
  console.log("Click");
};

ko.applyBindings();
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div>
  <div data-bind="template: 'header-template'"></div>

  <button data-bind="click: logClick">click listener in window</button>
</div>



<script id="header-template" type="text/html">

  <h1>A header inserted by template</h2>
  
</script>

通过此处的一些评论和额外的研究,我找到了我正在寻找的答案。

我的错误是认为 ko.applyBindings() 主要工作是将视图模型(javascript 对象)与视图(HTML 页面)相关联。虽然这是 applyBindings 作业中的 一个 ,但 applyBindings 开始呈现视图(HTML 页面) .在 Knockout 的世界中,呈现视图意味着(至少?)扫描 HTML 页面的 data-bind 属性,并处理这些属性。

就其本身而言,处理没有数据的 data-bind 属性会非常有用。但是,如果您使用的应用程序已创建 自定义绑定 (如 this tutorial 中所示),则调用 applyBindings 可以执行的操作没有限制。在我的特定情况下,Magento 2 有一个名为 scope 的自定义绑定,它(通过一些其他机制)将为特定节点上下文绑定数据。