简体   繁体   中英

Meteor class being fired multiple times from JQuery.click()

I have a generic template that I use multiple times.

{{#each item}}
   {{> genericTemplate}}
{{/each}}

Inside of this template I have a button that when it is clicked fires a hidden file input in the generic template.

 $(".upload").click();

Unfortunately for each template the ".upload" class gets fired. So if I had four items , it would give me 4 file inputs. I can't give the buttons a unique id="" because then I would have to explicitly define each event for each id, negating the entire reason for creating the generic template in the first place. What is the proper way to achieve something like this?

EDIT:

My template events look like this:

Template.generic.events({
   'click .fileUpload' : function () {
     $(".upload").click(); // sets off the 4 templates .upload class
   },
  'change .upload' : function (e) {
    console.log('upload')
   }
})

HTML:

<template name="generic">
   <!--Hidden Inputs that get fired on click events -->
   <div class="hiddenFile">
      <input type="file" class="upload"/>
   </div>

  <button class="btn btn-success fileUpload">UPLOAD FILE </button>
</template>

Try this trick :

Template.generic.events({
  'click .fileUpload' : function (event,template) {
    // fires only the template instance .upload
    template.$(".upload").click();
  },
  'change .upload' : function (e) {
    console.log('upload')
  }
});

You can use Template.instance to fire the event in only the appropriate instance:

'click .fileUpload' : function () {
  var template = Template.instance();
  template.$(".upload").click(); // should only set off this specific upload input.
}

That said, is there really no way you can achieve the same effect without manufacturing an event in the DOM? It's up to you, but can't you just run the code that's going to replace console.log('upload') directly?

Maybe smth like this?

Template.generic.events({
    'click .fileUpload' : function (event, target) {
       e.currentTarget.parent().find(".upload").click(); // sets off the 4 templates .upload class
    },
    'change .upload' : function (e) {
        console.log('upload')
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM