Reputation: 97
I'm having trouble getting my head around calling an internal function from inside another. I need to be able to call funcA on page load passing it an element and some dimensions which then applies some styles to the passes elem. funcB then uses said parameters to size the element correctly:
var funcA = function(elem, width, height) {
//performs layout restyle
function funcB() {
//performs sizing
}
funcB();
}
However, the issue is I need to recall funcB from within a debounced resize function like so.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
var resizeFn = debounce(function() {
funcB();
}, 10);
$(window).on('resize', resizeFn);
What's the best practice for making funcB available? I'd been considering returning it and then caching it to variable:
var funcA = function(elem, width, height) {
//performs layout restyle
function funcB() {
//performs sizing
}
funcB();
return funcB
}
var scopedFuncB = funcA;
scopedFuncB();
But is there a better way?
Upvotes: 0
Views: 51
Reputation: 664589
I'd been considering returning it
Yes, that's definitely best practise. So the caller can decide what do with it and when and how often to call it.
…and then caching it to variable
No need for that actually. You can directly pass it to debounce
without further ado:
$(window).on('resize', debounce(funcA(elem, width, height), 10));
Upvotes: 1
Reputation: 17616
Here are two options:
var funcA = function(elem, width, height) {
if(!(this instanceof funcA)){
return new funcA(elem, width, height);
}
//performs layout restyle
this.funcB = function() {
//performs sizing
}
}
funcA(elem, width, height).funcB();
or
var funcA = function(elem, width, height) {
//performs layout restyle
var funcB = function() {
//performs sizing
}
window.funcB = funcB;
}
funcA(elem, width, height);
funcB();
Upvotes: 0
Reputation: 621
Why don't you make funcA return something and then funcB does its stuff receiving that funcA's output as a parameter?
Upvotes: 0