Im trying to run an AJAX function based on which tab is currently active in my app. everything works fine when I call the function after certain events but I'm unable to invoke the function using a string variable, dynamically.
following this answer : https://stackoverflow.com/a/359910/5950111 I just receive a TypeError describing that the object Im calling is not a function.
this is my ajax function:
function home_tab_fetchMore(items_count) {
let request = new XMLHttpRequest();
let output = []
request.open('GET', `feedstream/${items_count}`);
request.onload = function () {
if (request.status === 200 && request.responseText != '') {
let new_items = JSON.parse(request.responseText);
for (let i = 0; i < new_items.length; i++) {
let item = new_items[i];
let event_id = feed_stream_row.children.length + 1;
let feed_item = htmlToElement(`
<div class="grid-item" id="eventcard_${event_id}">
<div class="card-header">Featured</div>
<div class="card-body">
<h5 class="card-title">${item.fields['title']}</h5>
<p class="card-text">${item.fields['appointment']}
<br>
${dummy_text.sentence(5, 40)}
</p>
</div>
</div>
`);
// appending new item to DOM and updating masonry laytout
feed_stream_row.appendChild(feed_item);
msnry.appended(feed_item);
output.push(feed_item);
}
} else {
console.log('no response!');
}
};
request.send();
return output;
};
and this is the caller event:
$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
var fnstring = `${current_active_tab().id}_fetchMore`;
var fn = window[fnstring]
console.log(typeof(fnstring)) // returns: string type
console.log(fnstring) // returns: home_tab_fetchMore without quotes
console.log(fn) // returns: undefined
fn(2) // returns: Uncaught TypeError: fn is not a function
// however, this line works just as expected:
home_tab_fetchMore(2)
};
});
There are also additional lines to the TypeError that I can't comprehend:
Uncaught TypeError: fn is not a function
at main.js:128
at dispatch (jquery-3.3.1.slim.min.js:2)
at v.handle (jquery-3.3.1.slim.min.js:2)
I appreciate any suggestion and guidance in advance, thank you.
function home_tab_fetchMore(items_count) {}
The above function definition won't be available in window
object unless it is called. Instead do with function expression(You can't use function expressions before you define them).
home_tab_fetchMore = function() {} OR
window.home_tab_fetchMore = function() {}