【问题标题】:Apply knockout bindings in specific context在特定上下文中应用淘汰赛绑定
【发布时间】:2013-10-09 09:35:04
【问题描述】:

我是 Require 的新手,也是 Knockout 的新手。现在我正在尝试将我的 Knockout 视图模型集成到 Reuire.js 架构中。

我有 5 个 js 文件:

  • /scripts/require.js
  • /scripts/jquery-2.0.3.js
  • /scripts/knockout-2.2.0.js
  • /scripts/app.js
  • /scripts/ko-model/MyViewModel.js

这就是我从 index.html 调用 require.js 的方式:

<script data-main="/scripts/app" src="/scripts/require.js"></script>

这里是入口点脚本 app.js:

require.config({
    baseUrl: "/scripts",
    paths: {
        "jquery": "jquery-2.0.3",
        "knockout": "knockout-2.2.0",
        "MyViewModel": "./ko-model/MyViewModel"
    }
});

require([
    "jquery",
    "knockout",
    "MyViewModel"
],
    function ($, ko, MyViewModel) {
        // LOGIC:
        $(function () {
            ko.applyBindings(
                new MyViewModel(),
                $("#myId")
            );
        });        
    });

这是 MyViewModel.js 模块:

define(
    'MyViewModel',
    ["knockout"],
    function (ko) {
        return function MyViewModel() {
            // MyViewModel implementation
            ...
        };
    });

这对我来说很好用。但是。

正如您在 app.js 中看到的那样,我有:

function ($, ko, MyViewModel) {
    // LOGIC:
    $(function () {
        ko.applyBindings(
            new MyViewModel(),
            $("#myId")
        );
    });
}

我不喜欢这样。我宁愿不要在这里使用 jQuery 并以某种方式指定淘汰赛上下文:

function ($, ko, MyViewModel) {
    // LOGIC:
    ko.applyBindings(
        new MyViewModel(),
        document.getElementById("myId")
    );
}

但在这种情况下,淘汰赛绑定不起作用。 document.getElementById("myId") 似乎在这里不起作用。我不知道为什么。 (我最好的猜测是在调用 ko.applyBindings() 时该文档尚未加载)。

因此我有下一个问题:

如何在 LOGIC 部分使用 jQuery 进行转义,但仍指定剔除上下文?

如果有任何改进我的代码的建议,我将不胜感激。

【问题讨论】:

    标签: javascript requirejs knockout-2.0


    【解决方案1】:

    是的,它找不到 id,因为很可能文档还没有完成加载。如果&lt;script&gt;s 在&lt;head&gt; 中,则很可能会出现此问题。您需要友好的解决方案是domReady plugin。来自文档:

    require(["jquery", "knockout", "MyViewModel", "domReady"],
    function($, ko, MyViewModel, domReady) {
        domReady(function () {
            // your code here, document is initialized
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2013-12-11
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 2013-10-31
      • 2013-08-14
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      相关资源
      最近更新 更多