Get DOM element using meteor template helpers

前端 未结 1 1701
面向向阳花
面向向阳花 2021-02-03 13:04

For example my html is


In met

相关标签:
1条回答
  • 2021-02-03 13:29

    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 };
      };
    }
    
    0 讨论(0)
提交回复
热议问题