Balaganapathy NT
Balaganapathy NT

Reputation: 47

RequireJs with Knockout

I tried to to use Knockout with require js but i could not able to bind data from 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"]);

main.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
    };
});

but i am getting the below error

Uncaught ReferenceError: Unable to process binding "text: function (){return myMessage }" Message: myMessage is not defined

Upvotes: 0

Views: 1293

Answers (2)

QBM5
QBM5

Reputation: 2788

You arent producing a class that can be constructed and return properties

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
      };
   };
});

Upvotes: 0

Roy J
Roy J

Reputation: 43899

You're calling appViewModel as a constructor (using new), but are creating a local variable viewModel inside it, instead of adding members to this, like this.myMessage = ko.observable();.

Upvotes: 2

Related Questions