Skip to content Skip to sidebar Skip to footer

Get Dom Element Using Meteor Template Helpers

For example my html is In meteor template helpers, I want to be able to

Solution 1:

Not in helpers, but in the rendered callback you can do:

Template.atest.rendered = function() {
  var el = this.find("[data-test]");
};

And in event handlers:

Template.atest.events({
  "click a": function( event, template ) {
    var selectEl = template.find("[data-test]"); // Arbitrary element in templatevar targetEl = event.target;                 // Element that triggered the eventvar currentEl = event.currentTarget;         // Element that is handling this event function (the element referenced by "click a")
  }
});

Of course, you could also do:

Template.atest.events({
  "click a[data-test]": function() {
    // ...
  }
});

If none of these options work for you, you might want to reevaluate your approach. Needing access to an element from a helper function indicates that you are trying to use a procedural coding style rather than a template-driven style. In general, don't store data on DOM nodes, store it in the template's context object.

Could you give some additional context on what exactly you're trying to do? There might be a better way.

Think about this: the helper has to be called in order to render the element. How would you be able to access the element if it doesn't even exist yet?

Edit: here is a template-driven approach to attaching href attributes to a template depending on where it is defined. Basically, you want to include the necessary data to generate the link template in any associated parent template. Then, just call the link template with that data:

HTML:

<body>
  {{> parent1}}
</body><templatename="parent1"><div>
    {{> link linkData}}
  </div><ul>
    {{#each arrayData}}
      <li>{{> link}}</li>
    {{/each}}
  </ul>

  {{#with arbitraryData}}
    {{> parent2}}
  {{/with}}

</template><templatename="parent2"><p>{{> link transformedData}}</p></template><templatename="link"><ahref="{{href}}">{{text}}</a></template>

JS:

if (Meteor.isClient) {
  Template.parent1.linkData = {
    href: "/path/to/something",
    text: "Parent Template 1 Link"
  };

  Template.parent1.arrayData = [
    { href: "array/path/1", text: "Array path one" },
    { href: "array/path/2", text: "Array path two" }
  ];

  Template.parent1.arbitraryData = {
    link: "/foo/bar/baz",
    name: "Parent Template 2 Link"
  };

  Template.parent2.transformedData = function() {
    return { href: this.link, text: this.name };
  };
}

Post a Comment for "Get Dom Element Using Meteor Template Helpers"