Get DOM Element Using Meteor Pattern Helpers
For example, my html
<template name="atest"> <a href="{{route}}" data-test="test">Click</a> </template> In the meteor pattern helpers, I want to be able to select an anchor tag.
Template.atest.route = function() { console.log(this.data-test); }; I am not sure if this can be done or not, but of course it cannot be done with any method that I tried. I know there is a way to pass an argument in an instance of a template, but I don't want this. I want to be able to select this anchor tag in which the template instance is located and do something with it.
Appreciate any help I can get.
Not in the helpers, but in the rendered 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 template var targetEl = event.target; // Element that triggered the event var currentEl = event.currentTarget; // Element that is handling this event function (the element referenced by "click a") } }); Of course, you can also:
Template.atest.events({ "click a[data-test]": function() { // ... } }); If none of these options work for you, you can reevaluate your approach. The need to access 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, do not store data on the DOM nodes, save it in the template context object.
Could you give an additional context of what exactly are you trying to do? Perhaps the best way.
Think about it: you need to call an assistant to render the item. How could you access an element if it does not already exist?
Edit: this takes a template approach to attaching href attributes to a template depending on where it is defined. Basically, you want to include the necessary data to create the link template in any associated parent template. Then just call the link template with this data:
HTML:
<body> {{> parent1}} </body> <template name="parent1"> <div> {{> link linkData}} </div> <ul> {{#each arrayData}} <li>{{> link}}</li> {{/each}} </ul> {{#with arbitraryData}} {{> parent2}} {{/with}} </template> <template name="parent2"> <p>{{> link transformedData}}</p> </template> <template name="link"> <a href="{{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 }; }; }