How to reference HTML level for javascript component?

I have a component that can be used several times on a page. And I would like to save the configuration of HTML and components.

<div id="myComponent">
   <table>
      <th>c1</th>
      ...
      <th>cX</th> 
   </table> 
</div>
<script>
  var componentApi = new MyModule.MyComponent($('#myComponent')[0]);
  // configure component through componentApi with ajax source and callback render funcions
</script>

But I am not happy with that. Firstly, because I don’t like to refer to the uniqueness of id (this makes the template complex), and secondly, I don’t like the unnecessary search for the identifier through the entire document.

But my all alternative ideas don't work:

  • I do not want to rely on scriptid either (to calculate the previous brother) for the same reasons.
  • And .currentScriptdoes not work in IE 11.
  • Divhas no event onLoad...

Do we have a better solution than searching for an identifier throughout the document, if only what we need initializes the component in HTML with an HTML layer?

. , HTML JS DRY. "". , -, data-, HTML. , HTML - HTML.

. , , " " ( ) "" . id . , , id HTML/DOM, , , id.

. , ( , ). " " + "-" , , - , Polymer polyfill?

+4
1

DRY ( ), script, .

class , , data-.

Eg.

<div class="component" data-config1="1" data-config2="2"> ... </div>
...
<!-- At end of HTML page -->
<script>
  $(".component").each(function(idx, elem)
  {
     var componentApi = new MyModule.MyComponent(elem);
     var $elem = $(elem);
     componentApi.config1 = $elem.data("config1");
     // etc...
     //configure component through componentApi 
  }
</script>

,

var myData = function(key){$elem.data(key);};

componentApi.config1 = myData("config1");
+3

Source: https://habr.com/ru/post/1617243/


All Articles