Using AMD modules with require.js











up vote
0
down vote

favorite












Using AMD modules for spring boot application (spring boot + Thymeleaf).
There are many approaches for loading AMD module and I am lost (+ annoyed). I am trying to follow best practices and applying what I learned so far.



Add User module => js/modules/add-user.js



define(['jquery', 'ajax-util'], ($, AjaxUtil) => {

'use strict';

const ADD_USER_MODAL = '#modal-add-user';
const USER_ID = '#user-name';
const USER_EMAIL = '#user-email';
const BTN_ADD_USER = '#btn-add-user';

let $modal;
let $userId;
let $userEmail;
let $addUserBtn;

function init(){
$modal = $(ADD_USER_MODAL);
$userId = $(USER_ID);
$userEmail = $(USER_EMAIL);
$addUserBtn = $(BTN_ADD_USER);
}

function getJsonPayload(){

let jsonObj = {
'userId' : $userId.val(),
'userEmail' : $userEmail.val()
};

let jsonString = JSON.stringify(jsonObj);

return jsonString;
}

let userModule = {

registerEvents: () => {

// initialize
init();

$modal.on('show.bs.modal'), (e) => {
$modal.find('input:text').val('');
});

$addUserBtn.click((e) => {

AjaxUtil.fetchData({method: 'POST', uri: 'user/add', payload: getJsonPayload(), callback: (response) => {

if(response.isError){
console.error('Failed to fetch data');
return;
}

let data = response.data;
}});
});
}
};

return userModule;
});




Question 1:



Should I use Approach 1 or Approach 2 below, and why?




js/app.js => Approach 1



require(['add-user'], (AddUser) => {

$(document).ready(function() {
AddUser.registerEvents();
});
});



js/app.js => Approach 2



$(document).ready(function() {

require(['add-user'], (AddUser) => {
AddUser.registerEvents();
});
});




Question 2:



In the head section of master-template.html below, I am loading amd-config.js synchronously just after require.js library. Is it ok? or should I put requirejs.config in top of app.js and use data-main attribute i.e.



<script data-main="app.js" th:src="@{/js/libs/require.js}"></script>


(best practice/recommendations are appreciated)



requirejs.config => js/amd-config.js



let ctxPath = $('meta[name="ctxPath"]').attr("content");
requirejs.config({
baseUrl : ctxPath + 'js',
paths : {
'add-user' : [ 'modules/add-user' ],
},
shim : {
'add-user' : {
deps : [ 'bootstrap' ]
}
}
});


master-template.html



<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>

<meta name="ctxPath" th:content="@{/}">

<script type="text/javascript" th:src="@{/js/libs/require.js}"></script>
<script type="text/javascript" th:src="@{/js/amd-config.js}"></script>

</head>

<body >



<!--/* ================ page footer ======================== */-->
<script type="text/javascript">
require([ 'app' ]);
</script>

</body>
</html>




Question 3:



Loading app.js at bottom of master-template.html, is it ok or should I use data-main attribute i.e.



<script data-main="app.js" th:src="@{/js/libs/require.js}"></script>









share|improve this question
























  • When you use jQuery with RequireJS, you should use it as an AMD module, not the global
    – Aluan Haddad
    Nov 9 at 20:39

















up vote
0
down vote

favorite












Using AMD modules for spring boot application (spring boot + Thymeleaf).
There are many approaches for loading AMD module and I am lost (+ annoyed). I am trying to follow best practices and applying what I learned so far.



Add User module => js/modules/add-user.js



define(['jquery', 'ajax-util'], ($, AjaxUtil) => {

'use strict';

const ADD_USER_MODAL = '#modal-add-user';
const USER_ID = '#user-name';
const USER_EMAIL = '#user-email';
const BTN_ADD_USER = '#btn-add-user';

let $modal;
let $userId;
let $userEmail;
let $addUserBtn;

function init(){
$modal = $(ADD_USER_MODAL);
$userId = $(USER_ID);
$userEmail = $(USER_EMAIL);
$addUserBtn = $(BTN_ADD_USER);
}

function getJsonPayload(){

let jsonObj = {
'userId' : $userId.val(),
'userEmail' : $userEmail.val()
};

let jsonString = JSON.stringify(jsonObj);

return jsonString;
}

let userModule = {

registerEvents: () => {

// initialize
init();

$modal.on('show.bs.modal'), (e) => {
$modal.find('input:text').val('');
});

$addUserBtn.click((e) => {

AjaxUtil.fetchData({method: 'POST', uri: 'user/add', payload: getJsonPayload(), callback: (response) => {

if(response.isError){
console.error('Failed to fetch data');
return;
}

let data = response.data;
}});
});
}
};

return userModule;
});




Question 1:



Should I use Approach 1 or Approach 2 below, and why?




js/app.js => Approach 1



require(['add-user'], (AddUser) => {

$(document).ready(function() {
AddUser.registerEvents();
});
});



js/app.js => Approach 2



$(document).ready(function() {

require(['add-user'], (AddUser) => {
AddUser.registerEvents();
});
});




Question 2:



In the head section of master-template.html below, I am loading amd-config.js synchronously just after require.js library. Is it ok? or should I put requirejs.config in top of app.js and use data-main attribute i.e.



<script data-main="app.js" th:src="@{/js/libs/require.js}"></script>


(best practice/recommendations are appreciated)



requirejs.config => js/amd-config.js



let ctxPath = $('meta[name="ctxPath"]').attr("content");
requirejs.config({
baseUrl : ctxPath + 'js',
paths : {
'add-user' : [ 'modules/add-user' ],
},
shim : {
'add-user' : {
deps : [ 'bootstrap' ]
}
}
});


master-template.html



<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>

<meta name="ctxPath" th:content="@{/}">

<script type="text/javascript" th:src="@{/js/libs/require.js}"></script>
<script type="text/javascript" th:src="@{/js/amd-config.js}"></script>

</head>

<body >



<!--/* ================ page footer ======================== */-->
<script type="text/javascript">
require([ 'app' ]);
</script>

</body>
</html>




Question 3:



Loading app.js at bottom of master-template.html, is it ok or should I use data-main attribute i.e.



<script data-main="app.js" th:src="@{/js/libs/require.js}"></script>









share|improve this question
























  • When you use jQuery with RequireJS, you should use it as an AMD module, not the global
    – Aluan Haddad
    Nov 9 at 20:39















up vote
0
down vote

favorite









up vote
0
down vote

favorite











Using AMD modules for spring boot application (spring boot + Thymeleaf).
There are many approaches for loading AMD module and I am lost (+ annoyed). I am trying to follow best practices and applying what I learned so far.



Add User module => js/modules/add-user.js



define(['jquery', 'ajax-util'], ($, AjaxUtil) => {

'use strict';

const ADD_USER_MODAL = '#modal-add-user';
const USER_ID = '#user-name';
const USER_EMAIL = '#user-email';
const BTN_ADD_USER = '#btn-add-user';

let $modal;
let $userId;
let $userEmail;
let $addUserBtn;

function init(){
$modal = $(ADD_USER_MODAL);
$userId = $(USER_ID);
$userEmail = $(USER_EMAIL);
$addUserBtn = $(BTN_ADD_USER);
}

function getJsonPayload(){

let jsonObj = {
'userId' : $userId.val(),
'userEmail' : $userEmail.val()
};

let jsonString = JSON.stringify(jsonObj);

return jsonString;
}

let userModule = {

registerEvents: () => {

// initialize
init();

$modal.on('show.bs.modal'), (e) => {
$modal.find('input:text').val('');
});

$addUserBtn.click((e) => {

AjaxUtil.fetchData({method: 'POST', uri: 'user/add', payload: getJsonPayload(), callback: (response) => {

if(response.isError){
console.error('Failed to fetch data');
return;
}

let data = response.data;
}});
});
}
};

return userModule;
});




Question 1:



Should I use Approach 1 or Approach 2 below, and why?




js/app.js => Approach 1



require(['add-user'], (AddUser) => {

$(document).ready(function() {
AddUser.registerEvents();
});
});



js/app.js => Approach 2



$(document).ready(function() {

require(['add-user'], (AddUser) => {
AddUser.registerEvents();
});
});




Question 2:



In the head section of master-template.html below, I am loading amd-config.js synchronously just after require.js library. Is it ok? or should I put requirejs.config in top of app.js and use data-main attribute i.e.



<script data-main="app.js" th:src="@{/js/libs/require.js}"></script>


(best practice/recommendations are appreciated)



requirejs.config => js/amd-config.js



let ctxPath = $('meta[name="ctxPath"]').attr("content");
requirejs.config({
baseUrl : ctxPath + 'js',
paths : {
'add-user' : [ 'modules/add-user' ],
},
shim : {
'add-user' : {
deps : [ 'bootstrap' ]
}
}
});


master-template.html



<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>

<meta name="ctxPath" th:content="@{/}">

<script type="text/javascript" th:src="@{/js/libs/require.js}"></script>
<script type="text/javascript" th:src="@{/js/amd-config.js}"></script>

</head>

<body >



<!--/* ================ page footer ======================== */-->
<script type="text/javascript">
require([ 'app' ]);
</script>

</body>
</html>




Question 3:



Loading app.js at bottom of master-template.html, is it ok or should I use data-main attribute i.e.



<script data-main="app.js" th:src="@{/js/libs/require.js}"></script>









share|improve this question















Using AMD modules for spring boot application (spring boot + Thymeleaf).
There are many approaches for loading AMD module and I am lost (+ annoyed). I am trying to follow best practices and applying what I learned so far.



Add User module => js/modules/add-user.js



define(['jquery', 'ajax-util'], ($, AjaxUtil) => {

'use strict';

const ADD_USER_MODAL = '#modal-add-user';
const USER_ID = '#user-name';
const USER_EMAIL = '#user-email';
const BTN_ADD_USER = '#btn-add-user';

let $modal;
let $userId;
let $userEmail;
let $addUserBtn;

function init(){
$modal = $(ADD_USER_MODAL);
$userId = $(USER_ID);
$userEmail = $(USER_EMAIL);
$addUserBtn = $(BTN_ADD_USER);
}

function getJsonPayload(){

let jsonObj = {
'userId' : $userId.val(),
'userEmail' : $userEmail.val()
};

let jsonString = JSON.stringify(jsonObj);

return jsonString;
}

let userModule = {

registerEvents: () => {

// initialize
init();

$modal.on('show.bs.modal'), (e) => {
$modal.find('input:text').val('');
});

$addUserBtn.click((e) => {

AjaxUtil.fetchData({method: 'POST', uri: 'user/add', payload: getJsonPayload(), callback: (response) => {

if(response.isError){
console.error('Failed to fetch data');
return;
}

let data = response.data;
}});
});
}
};

return userModule;
});




Question 1:



Should I use Approach 1 or Approach 2 below, and why?




js/app.js => Approach 1



require(['add-user'], (AddUser) => {

$(document).ready(function() {
AddUser.registerEvents();
});
});



js/app.js => Approach 2



$(document).ready(function() {

require(['add-user'], (AddUser) => {
AddUser.registerEvents();
});
});




Question 2:



In the head section of master-template.html below, I am loading amd-config.js synchronously just after require.js library. Is it ok? or should I put requirejs.config in top of app.js and use data-main attribute i.e.



<script data-main="app.js" th:src="@{/js/libs/require.js}"></script>


(best practice/recommendations are appreciated)



requirejs.config => js/amd-config.js



let ctxPath = $('meta[name="ctxPath"]').attr("content");
requirejs.config({
baseUrl : ctxPath + 'js',
paths : {
'add-user' : [ 'modules/add-user' ],
},
shim : {
'add-user' : {
deps : [ 'bootstrap' ]
}
}
});


master-template.html



<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>

<meta name="ctxPath" th:content="@{/}">

<script type="text/javascript" th:src="@{/js/libs/require.js}"></script>
<script type="text/javascript" th:src="@{/js/amd-config.js}"></script>

</head>

<body >



<!--/* ================ page footer ======================== */-->
<script type="text/javascript">
require([ 'app' ]);
</script>

</body>
</html>




Question 3:



Loading app.js at bottom of master-template.html, is it ok or should I use data-main attribute i.e.



<script data-main="app.js" th:src="@{/js/libs/require.js}"></script>






javascript require.js






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 at 7:27









200_success

127k15148410




127k15148410










asked Nov 7 at 9:13









Hassan Tareq

992




992












  • When you use jQuery with RequireJS, you should use it as an AMD module, not the global
    – Aluan Haddad
    Nov 9 at 20:39




















  • When you use jQuery with RequireJS, you should use it as an AMD module, not the global
    – Aluan Haddad
    Nov 9 at 20:39


















When you use jQuery with RequireJS, you should use it as an AMD module, not the global
– Aluan Haddad
Nov 9 at 20:39






When you use jQuery with RequireJS, you should use it as an AMD module, not the global
– Aluan Haddad
Nov 9 at 20:39

















active

oldest

votes











Your Answer





StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");

StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f207128%2fusing-amd-modules-with-require-js%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















 

draft saved


draft discarded



















































 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f207128%2fusing-amd-modules-with-require-js%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Сан-Квентин

8-я гвардейская общевойсковая армия

Алькесар