I’ve built a small carousel from a simple no frills js library, Siema - works ok. The problem is when I try and use this carousel within Mustache (JS template engine) I run into a small issue of
Uncaught Error: Something wrong with your selector
I’ve used Mustache before using jQuery and basic click events
Example
This works when not using MustacheJS $('.more').on('click', function() {}
But when using MustacheJS - I need to add $(document) $(document).on('click', '.more', function () {}
Which got me thinking, I need to add something extra for the carousel to work.
The first fiddle below shows the working instance without Mustache.
The second fiddle is using Mustache which is the problem (view console and the error is present).
You’re trying to instantiate the carousel before the markup got rendered, so there is no element that matches the .siema selector; to fix this, simply move the new Siema() part after the .render() call.
That’s called event delegation (also explained here with jQuery); in short, by adding an event listener to an element you’ll also get notified by children of that element dispatching the same event. This is particularly useful if you have dynamically added children such as rendered by mustache, as you only have to add a single event listener once to a given parent element (in case of doubt, the document).
Siema however doesn’t support event delegation; it needs an element to hook into from the start, so that it can apply the necessary inline styles etc.
Just to clarify, this wasn’t meant to be dismissive – plugins like this generally don’t work like that. The carousel has to be instantiated so that it can prepare the DOM; for example, it wraps the slides in a container, and clones a number of slides into it if looping is desired. This is hardly practical (if even possible) to do on the fly.
And even with much simpler plugins that don’t require such preparations and could technically work with global event delegation too (say, a tab component) it makes more sense to create them explicitly; this way you can initially store certain element references (such as tab / content relations), and don’t have to query for them anew all the time.