简体   繁体   中英

How to use RequireJS with Knockout

My setup so far:

<script src="/common/js/require.configure.js"></script>
<script src="/common/js/lib/require.js" data-main="/common/js/app.js"></script>

require.configure.js

var require = {
baseUrl: '/',
paths: {
    "jquery": "/common/js/lib/jquery",
    "fastclick": "/common/js/lib/fastclick",
    "knockout": "/common/js/lib/knockout",
    "common": "/common/js/scripts/common"
}
};

The top three paths are obviously just libraries that I am using for my application. The last file "common" is a collection of functions that are global to my application such as opening the main menu, giving messages to the user, or binding handlers, etc.

app.js

define(["jquery", "knockout", "fastclick", "common"], function (){

});

I know that requireJS always needs a data-main file to run initially. But what does this above code really do? I trying to follow tutorials online but it is not helping. I'm guessing that by defining those strings in the array, it looks it up in the configuration file and is loading in those files, but how are those files then accessed or used? I'm guessing that I can simply then just "require" those same strings and they will be available to me in my functions?

common.js (simplified for Stack Overflow)

require(["knockout"], function (ko) {

var appViewModel = {};
appViewModel.loaded = ko.observable(false);

});

By wrapping everything in the require() I think that this is injecting the dependencies of needing knockout.

App's First Page - login.html (simplified for SO)
In the first page of the app, I define a <script> tag with the following

require(["jquery", "knockout", "fastclick", "common"], function ($, ko, FastClick)
{
    $(function(){
        appViewModel.loginData = {
            email : ko.observable(),
            password : ko.observable()
        };
    });
 });

And the resulting error when trying to run is that

Uncaught ReferenceError: appViewModel is not defined

despite the fact that I have included "common" in the require([]).

What am I missing here? I think that I may be completely misunderstanding what "require" and "define" do in requireJS, so that would be a good basis of an answer for me.

i think you want to do something like that:

Modules that define global obj

  require(["knockout"], function (ko) {
     window.appViewModel = {};
     window.appViewModel.loaded = ko.observable(false);

 });

Modulw that popule the obj:

 require(["jquery", "knockout", "fastclick", "common"], function ($, ko, FastClick)
{
    window.appViewModel.loginData = {
    email : ko.observable(),
    password : ko.observable()

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM