I'm interested in learning how to manipulate a JS object from one file into another asynchronously, as my experience with asynchronous code principles is limited.
Scenario:
In my app.js
file, I dynamically generate 'app panels' based on my HTML structure.
$("div.app-panel[data-panel]").each(function() {
// create panel objects for all html divs with class app-panel
var panel = {};
panel.div = $(this);
panel.name = $(this).attr("data-panel");
panel.isActive = ($(this).attr("data-active-panel") == "true" ? true : false);
panel.onActive = () => {
// default functionality to execute when activating an app panel
panel.isActive = true;
$(panel.div).attr("data-active-panel", true);
};
panel.onInactive = () => {
// default functionality to execute when deactivating an app panel
panel.isActive = false;
$(panel.div).attr("data-active-panel", false);
};
app.panels.push(panel);
});
Now, I want to override the onActive method in my other file, main.js
. How can I ensure that this code has finished running? Using .filter()
or .find()
on app.panels returns undefined. While console.log(app.panels)
logs the array to the console, trying to access a specific panel like panel = app.panels[0]
results in undefined.
I attempted to define a function within the app
object which takes a callback function utilizing app.panels as a parameter, yet it yielded the same outcome...
Then, I tried a different approach:
app.getPanels = async () => {
return new Promise(function(resolve, reject) {
resolve(app.panels);
});
};
var getPanels = async (callBack) => {
const appPanels = await app.getPanels();
console.log(appPanels);
callBack(appPanels);
}
However, I encountered the error "TypeError: object is not iterable." It seems clear from my code that my understanding of promises is lacking. What am I overlooking?