Get DOM element using meteor template helpers

泪湿孤枕 提交于 2019-12-02 21:10:55

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 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 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>

<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 };
  };
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!