Search code examples
javascriptboilerplatejs

Best practice to avoid element name conflicts in views - BoilerplateJS


Imagine you have several components in your application, each having its own view.

While the components are independent, their views may use the same identifiers for DOM elements, e.g. there is a chance that 2 or more components would have views with similar input control like:

<label for="Bid">Bid</label>
<input type="text" id="Bid" name="Bid" value="0"/>

After components are activated, their views are attached to the DOM by Boiler.ViewTemplate, and now there's a name conflict for Bid element, causing side effects, e.g. clicking on the label works only in 1 view, and is disabled in the others.

What is the best practice to avoid such collisions? Should i use "unique" suffix/prefix for all elements in my views, like id="ComponentName_Bid"? Or there is more elegant solution?


Solution

  • This is indeed a very good question. I too struggled with it many times. Sometime back I did an implementation of giving an auto generated unique id for every ViewTemplate instance.

    • This UID could be used from JS logic (viewmodel.js etc) by passing it from the ViewTemplate instance.
    • This could be used by view.html as well as by the component specific .css file as a tag {comp.uid} which will be replaced by a special ViewTemplate logic, just as used for 'nls' replacement (see line 105 at view-template.js).

    That ofcourse worked, but the complexity was too much for the developers to understand. So in a later version of BoilerplateJS I removed this functionality and let developers to manage the elementIDs manually as you have suggested above.

    I still do not know what the best approach for this.. but for the moment I believe managing it manually results in a much cleaner code.