Hi there
- was wondering if it is possible to “cache” dom elements.
I have a stimulus controller with some targets. Users play around and manipulate the dom. After all this is done, they might want to go back and revert to a clean state as it was in the beginning. some psuedo code can be used to illustrate this:
connect(){
this.cachedSlides = this.slideTargets.map((x) => {return x}) // how to save the values of these DOM elements here?
this.editTargets() // we change the inner HTML
// elements of all the slide Targets
}
startAfresh(){
this.slideTargets.forEach((slide) => {
let cachedSlide = this.getCachedSlide(slide);
slide.innerHTML = cachedSlide.innerHTML; // this does not work
// the old html elements are not cached here
}, this);
}
was wanting to know how we could start afresh with the original dom elements? any pointers would be much appreciated.
chrs
Ben
You might be able to do this with a html template tag.
https://www.w3schools.com/TagS/tag_template.asp
- Create a template with the original slide content.
- On connect, copy the template to the page using a target (this is what the user will see).
- The user interacts with the content
- On click of some button, replace the copied slides with the template once more by using the same target
(I’m on my phone so writing a comprehensive example is hard. Sorry!)
1 Like
Maybe I’m not understanding the full context here, but it sounds a lot like you just want to reload your template, which is coming from the page where you’re mounting your controller. Why not just throw this in a Turbo frame and trigger a reload with “_top”, which will restore your original template?
Turbo frame reference
Otherwise, you’d probably want to do your cachedSlides on initialize() rather than connect(), so that your assignment only happens once.
@pinzonjulian @strobilomyces thank you all i appreciate your responses; I will consider and review
-
wrapping in a turbo frame might be a very viable option - that way all the state lives on the browser, instead of “caching” dom elements which might be updated in time.
-
templating is an interesting option - a tool for another day, perhaps, given the turbo frame options above.