I always end with huge "script.js" or "main.js" file in my project with one document.ready function and always feel bad about it, but dont know how to organize js/jquery code well on my own. Im familiar with concepts of modules but again dont know how to do it.
So for example, im working on project where i have a many resources(e.g. organisations, users, etc). I will do my best to show minimum of code of what i need to do with every 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(/*some_url_for_deleting_resource */, $(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 similar things with 10 resources and to put that code in the same script, how to fight against that, how to encapsulate and organize this example in modules code well?
EDIT 1: After doing some research i can guess that i need to go with requirejs (multipage), like: https://github.com/requirejs/example-multipage. So basically for every resource (organisations, users, blabla1, blabla2, etc) i need to have main.js file? Can someone provide example-basic concept of code, how to do this using requirejs?