code2use
code2use

Reputation: 56

Requirejs with jquery in Single Page Application

I am learning RequireJS, in the process I am stuck with the below problem:

I am trying to implement a single page application. Below scenario considered is similar to actual problem.

Index.html

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<script src="require.js" data-main="main.js"></script>
</head>
<body>
    <button id="start">Start</button>
    <div id="buttonContainer"></div>
</body>
</html>

main.js

require([  'jquery' ], function( $) {
    $(function() {
        $("#start").click(function() {
            $("#buttonContainer").load("page1.html");
            require(['module1'],function(){});
        }); 
    });
});

page1.html

<div>
    <button id="button_1">Click Me!!</button>
</div>

module1.js

define(['jquery'],function($){
    $(function(){
        $("#button_1").click(function(){
            $("#buttonContainer").load("page2.html");
        require(['module2'],function(){});
        });
    });
});

page2.html

<div>
    <button id="button_2">Back</button>
</div>

module2.js

define(['jquery'],function($){
    $(function(){
        $("#button_2").click(function(){
            $("#buttonContainer").load("page1.html");
        require(['module1'],function(){});
        });
    });
});

On click of start in index.html the div is populated with Click me!!, on click of Click me!! the div is populated with Back button and on click of Back button again Click me!! is populated and viceversa.

On jquery load of html, I am calling require()..to call respective js function for html. Is my approach correct??

Upvotes: 0

Views: 934

Answers (1)

Louis
Louis

Reputation: 151401

Your approach is wrong. Your code would work if requiring module1 and module2 would execute the module's factory every time your code requires the modules. However, the way RequireJS works, a module's factory is executed only the first time a module is required. (The "factory" is the callback you pass to define when defining a module.)

It's not clear to me what warrants dividing the code into modules the way it is done in the question. It seems unnecessary.

If there is a reason to divide into modules the way it is done in the question, then I would make the modules act on the page only when function is called. Then module1.js could be something like:

define(['jquery', 'module2'], function ($, module2) {
    return function () {
           // Whatever actions I want...
    };
});

module2 would be structured like module1. main.js would be something like:

require(['jquery', 'module1'], function ($, module1) {
    $(function () {
        [...]
         // This calls the function you returned when defining module 1.
        module1();
        [...]
    });
});

Upvotes: 1

Related Questions