I'm trying to build a micro JS library to emulate InDesign text threading on the web using this constructor pattern boilerplate. The idea is the user feeds the function DOM selectors in a desired order, e.g.
var thread=new TextThread(['#container1','#container2']);
thread.build();
And from there the library splits the text contents of the first container into spans for each word. When a word is out of view, the library will move it to the following container in the order.
Here's where IntersectionObserver comes in: I need to assign an observer to each container fed to the constructor, and then have it observe the spans inside it. When a span goes out of view, it fires the observer callback, which should loop through all the observers with the .takeRecords() method to check which spans are out of view in each container. I've gotten the observers to fire their callbacks with no problem, but the issue is referencing all the observers within the callback.
What I've tried is storing an array variable in the self-executing function from the boilerplate, and then when the constructor is built, it pushes the observers to that array.
var observers=[];
var Constructor = function (selectors) {
/*placeholder for code that selects and assigns the containers*/
containers.forEach((item, i) =>{
var options={
root: item,
rootMargin: '0px',
threshold: 1.0
}
var newObserver=new IntersectionObserver(callback,options);
observers.push(newObserver);
})
};
Then when the text is split into spans by word
words.forEach((word,w) =>{
observers[ current container index ].observe(word); });
In the callback, entries for the observer that fired the callback are visible. However, if I try to reference the other observers using my observers array variable, takeRecords() returns an empty array. Here's the callback I'm testing:
function callback(entries){
//the entries for the observer firing the callback are returning correctly
console.log(entries)
//the forEach below doesn't work though. It returns an empty array for each observer.
observers.forEach((item, i) => {
console.log(item.takeRecords())
});
}