I always end up with a huge "script.js" or "main.js" file in my project with a single document.ready function and always feel bad, but don’t know how to properly organize my own js / jquery code. I am familiar with the concepts of modules, but again I do not know how to do this.
So, for example, im is working on a project where I have a lot of resources (for example, organizations, users, etc.). I will do my best to show the minimum code of what I need to do with each resource:
function deleteResource(url, $that) {
$.ajax({
url: url,
type: "DELETE"
}).done(function() {
$that.closest('tr').remove();
});
}
function emptyHelper(element) {
if(typeof element === "undefined")
return "/";
return element;
}
function createHtml(data) {
var $that = $('.organisations-table tbody');
$that.find("tr").remove();
for(var i=0; i<data.length; i++) {
var element = "<tr>";
element += "<td>" + emptyHelper(data[i].telephone) + "</td>";
element += "<td><a href='#' class='delete-organisation' data-id=" + data[i].organisationId + "></a></td>"
element += "</tr>";
$that.append(element);
}
}
$("tbody").on('click', 'a.delete-organisation', function() {
deleteResource(, $(this));
});
$('#organisation-search').submit(function(event) {
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: "GET",
data: $(this).serialize()
}).done(function(data) {
createHtml(data);
});
});
Now imagine that I need to do such things with 10 resources and put this code in the same script, how to deal with this, how to properly encapsulate and organize this example in code modules?
EDIT 1: , requirejs (multipage), : https://github.com/requirejs/example-multipage. (, , blabla1, blabla2 ..) main.js?
- , , requirejs?