【问题标题】:RequireJs with KnockoutRequireJs 与 Knockout
【发布时间】:2016-12-28 23:54:52
【问题描述】:

我尝试将 Knockout 与 require js 一起使用,但我无法从 viewmodel 绑定数据。

HTML

<!doctype html>
<html lang="en">
<head>
    <title>SPA</title>
    <!-- Load the script "js/main.js" as our entry point -->
    <script data-main="js/app" src="js/lib/require.js"></script>
</head>
<body>

Today's message is: <span data-bind="text: myMessage"></span>

</body>
</html>

app.js

requirejs.config({
    "baseUrl": "js/lib",
    "paths": {
      "app": "../app",
      "jquery": "jquery",
      "knockout-3.4.0":"knockout-3.4.0",
      "custom":"../custom/custom-script",
      "customKO":"../custom/custom-knockout"

    }
});
require(['knockout-3.4.0', 'customKO'], function(ko, appViewModel) {
    ko.applyBindings(new appViewModel());
});
// Load the main app module to start the app
requirejs(["app/main"]);

ma​​in.js

define(["jquery", "knockout-3.4.0", "jquery.alpha", "jquery.beta" , "custom" , "customKO"], function($ , ko) {
    //the jquery.alpha.js and jquery.beta.js plugins have been loaded.
    $(function() {
        $('body').alpha().beta();

    });

});

custon-knockout.js

//Main viewmodel class
define(['knockout-3.4.0'], function(ko) {
    return function appViewModel() {
      var viewModel = {
        myMessage: ko.observable() // Initially blank
    };
    viewModel.myMessage("Hello, world!"); // Text appears
    };
});

但我收到以下错误

未捕获的 ReferenceError:无法处理绑定“文本:函数 (){return myMessage }” 消息:myMessage 未定义

【问题讨论】:

    标签: javascript knockout.js requirejs


    【解决方案1】:

    您将appViewModel 作为构造函数调用(使用new),但在其中创建了一个局部变量viewModel,而不是向this 添加成员,例如this.myMessage = ko.observable();

    【讨论】:

      【解决方案2】:

      你没有生成一个可以构造并返回属性的类

      define(['knockout-3.4.0'], function(ko) {
          return function appViewModel() {
              var self = this;
              self.myMessage: ko.observable() // Initially blank
              self.myMessage("Hello, world!"); // Text appears
            };
         };
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-15
        • 2014-03-06
        • 2021-12-27
        • 2016-04-16
        • 2015-11-09
        • 2015-08-15
        • 2016-09-05
        • 2013-03-05
        相关资源
        最近更新 更多