Reputation: 156
I'm attempting to call a function that already works with event listeners.
For example I set my event listener:
$('#country_choice').on('change', {opt: 1}, revealOption);
and the revealOption function contains a switch statement:
function revealOption(event){
var n = event.data.opt;
switch(n) {
case 1:
// 1 reveal city
$('#city_form').removeClass('hidden');
//alert( "Reveal city" );
break;
case 2:
// 2 reveal produce
$('#prod_form').removeClass('hidden');
//alert( "Reveal prod" );
break;
case 3:
// 3 reveal all
$('#city_form').removeClass('hidden');
$('#prod_form').removeClass('hidden');
alert( "Reveal all" );
break;
}
}
However, I'm trying to be able to use this function within other functions that aren't part of the event handler.
function dev(){
revealOption(3);
}
I'd prefer to avoid writing another function to do the same task, but finding it difficult to find out whether it's possible.
The closest question I've found while researching on SO is function handle jQuery event and parameter?, however this deals with passing the event object through to another function, not passing a value.
Any help would be gratefully appreciated :)
Upvotes: 1
Views: 1757
Reputation: 15403
Or else simply using ternary operator to check like this
var n = (event.data && event.data.opt) ? event.data.opt : event;
Upvotes: 0
Reputation: 133453
I would rather keep it simple and change the revealOption
method to accept option.
function revealOption(n) {
switch (n) {
...
}
}
$('#country_choice').on('change', {
opt: 1
}, function (event) {
revealOption(event.data.opt);
});
function dev() {
revealOption(3);
}
Upvotes: 0
Reputation: 318352
You'd have to either pass the same object
var evt = {
data : {
opt : 3
}
}
function dev(){
revealOption(evt);
}
Or change the function to check for both an event object and an integer or string or something else etc.
function revealOption(event){
var n = typeof event === 'object' ? event.data.opt : event;
Then you could call it as
revealOption(3)
If you want to pass custom objects as well, you'd have to check for some property of the object that is unique to the event object etc.
Upvotes: 2