Hi all
Trying to build a basic if else function which will hold a selection of variables depending on what type it is.
The below snippet will eventually hold about 7 or 8 different variables for each type, so I can access them in different functions and click events.
I was wondering if I should return an object or array, which is best?
And is the below correct - remove for improvement?
var whatQueryType = function (type) {
if (type === "a")
{
var title = "A Tilte"
var copy = "A description"
var url = "www.example.com/page-a"
return { title: title, copy: copy }
}
else if (type === "b")
{
var title = "B Title"
var copy = "B description"
var url = "www.example.com/page-b"
return { title: title, copy: copy }
}
else {
var title = "Random Title";
var copy = "Random description";
var url = "www.example.com/random"
}
}
Now in a separate function I might have the below. This will need the variables from the whatQueryType
function for a number of things: maybe ajax urls, page titles and page descriptions. But things are building up. Code becoming messy. I would like to simply drop the function inside any function, pass the query type and have access to all the variables.
Say we have a simple click event
$(document.body).on('click', '.item', function(e){
//instead of this
if (type === "a")
{
var title = "A Tilte"
var copy = "A description"
var url = "www.example.com/page-a"
}
...
//I would like to use and get access to all the variables using
whatQueryType("b")
//I realise I can
console.log(whatQueryType("b").url)
//what is the correct way to add the url variable to something like
$.ajax({
url: url,
dataType: 'json'
})
//I mean, do I need to do this every time I want a variable?
$.ajax({
url: whatQueryType("b").url,
dataType: 'json'
})
}
Again, is the the best/correct way of doing this?
Seem to be doing a lot of DRY so trying to reduce this and create a reusable function I can use.
I understand this is very trivial for some, just want to make sure I’m doing things correctly.
Thanks, Barry