Automatic node finding

Like jQuery with its $ function, Polymer also has a very handy way to locate nodes in the DOM of the page. This recipe shows you how to use it. You can find the code in the project find_nodes.

How to do it...

  1. The script starts with webindex.html, where a component with the name find-nodes is imported through the following line:
    <link rel="import"href="find_nodes.html">

    From this, we know that the component is defined in find_nodes.html, and the code behind it is in a file named find_nodes.dart. For a discussion of the other tags, refer to the first recipe.

  2. The code for find-nodes is defined in find_nodes.dart:
    import'dart.html';
    import'package:polymer/polymer.dart';
    
    @CustomTag('find-nodes')
    classFindnodes extends PolymerElement {
      Findnodes.created() : super.created();
      
      btnclick(MouseEvent  e, var detail, Node target) {
        // making the paragraph visible:
        $['show'].style
        ..display = 'inline'
        ..color = 'red';
        // changing the text inside the div:
        Element insideDiv = $['findme'];
        insideDiv.text = 'I was looked up by $ and changed!';
      }
    }
  3. The structure of the component is outlined in find_nodes.html:
    <link rel="import"href="packages/polymer/polymer.html">
    <polymer-element name="find-nodes">
    <template>
    <div class="auto-style1">
    <div id="findme">Hello from inside a div</div>
    <button on-click="{{btnclick}}">Click to find</button>
    </div>
    <p id="show" style="display:none">==&gt; I was found by $ and became visible! </p>
    </template>
    <script type="application/dart"src="find_nodes.dart"></script>
    </polymer-element>

The following screenshot shows you what you will see when you run the app:

How to do it...

Binding with a select field

How it works...

In step 2, we see that the paragraph with ID show is shown when the button is clicked because of the line $['show'].style.display = 'inline'; in the event handler. Likewise, an element reference to <div> with the ID findme is found with $['findme']. The code uses automatic node finding, a Polymer feature, to get a reference to each HTML element. Every node in a custom element (so inside the shadow DOM!) that is tagged with an id attribute can be referenced by its ID using the syntax $['ID'].

Note

This example requires Polymer dart 0.8.0 or higher.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset