Hi all,
Been learning a lot over the past weeks, thanks to all the help I’ve received in the forums here
I’ve come to the stage that I’ve built a lot of functions and AJAX/getJSON requests — which seem to be doing a lot of the same things.
DRY is certainly visible.
Hoping to build a couple of modules or some sort of javascript object(s) I can use and simply pass some variables/parameters. Take things to the next level
Ok, starting with an example.
I have a number of the same click events, the only thing that will change is the selector:
$(document).on('click', '#results .single', function(e){
});
$(document).on('click', '.more', function(e){
});
$(document).on('click', '#results .change', function(e){
});
$(document).on('click', '.home', function(e){
});
Is this a good time to build a useable function?
And within these click events, amongst other things I have either a single AJAX request, or getJSON files with promise.
getJSON example
I have at least four of the below which use nearly identical code, beside the url
and template
the code is the same which is becoming extremely busy.
$(document).on('click', '.more', function(e){
//...
// getJSON
// This set up calls two json files, one after the other
$.getJSON(urlOne, function(data) {
$.extend(data, funcs);
var template = $('#tplOne').html();
var html = Mustache.render(template, data, partials);
$("#resultsOne").html(html);
})
.then(
$.getJSON(urlTwo, function(data) {
$.extend(data, funcs);
var template = $('#tplTwo').html();
var html = Mustache.render(template, data);
$('#resultsTwo').html(html);
//... Will need to add extra variables and stuff here in some instances.
}));
});
Ideally, wondering best way/how to build a reusable click event function, and a getJSON function I can add into this click event, or build one big useable function
Great to hear advice or examples of best way of doing this.
Thnaks.
Barry