There may be a better way of doing this, but currently I have an nicely encapsulated, JavaScript object which can have some configurable options. I include a chunk of HTML code on a page (via Dreamweaver 'snippets'), and on page load my JS file runs through the DOM and identifies any of those code chunks as a particular functionality, and goes ahead and sets that functionality up.
That's all fine up until I wish to add more than one object on a page, and have them be configurable. The important point here is that you can add as many of these objects onto a page as you like with my current setup - because they're generic at that point, and have no 'id' attribute.
Now I wish to configure these objects, so I thought, "How about an external file containing the config settings, which these objects check for and apply if a config object is found". This works fine too, but the config data feels a bit 'removed' now. I imagine this will be annoying for my other colleagues eventually, it's just another Thing To Remember.
So to my question, I'm happy to insert these code blocks which will still trigger self-instantiating objects on page load - but what I'd like to try is also inserting a script block which contains the config settings. I need a means of that inserted code block knowing that its parent element is the context for configuration.
Example code:
<div class="snippet">
<_contents of this 'snippet'_/>
<script type="text/javascript">
new Snippet().init({
rootElement: REFERENCE_TO_THIS_SCRIPT_TAGS_PARENT_NODE,
configOptionA: true,
configOptionB: false
});
</script>
</div>
Note: The <div class="snippet">
has no 'id' attribute on purpose, because I want to allow for more than one of these to be dropped onto a page.
Other solutions welcome, so long as they adhere to my few restrictions!
My other related question (now answered) addresses this now, essentially I ended up with:
...and then in a script loaded on every page, which scans for any appropriate elements to instantiate and config:
For a more complete context of the above code;
Now that my inserted 'chunks' of content have no id attribute, and dynamically evaluated, contextual config objects - I am free to add as many variants as I like. My only real concern is performance if a whole bunch of these Snippet() objects are added to my page (not likely).