Search code examples
arraysmongodbmeteormeteor-blaze

Get element from array from html-file


I'm using meteor (version 1.8) with blaze.js and mongodb.

I'm trying to use an array-element which looks like this on the html file:

{{#each name in chatMeta.lastWhisp}}
 <div class="WhisperCharacter">
  {{name}}  
 </div>
{{/each}}

The corresponding helper for this query looks like this:

chatMeta() {
return ChatMeta.findOne({});
},

The collection that gets queried has an array "lastWhisp"

"lastWhisp": ["StringA", "StringB"]

I'm trying to get the information of {{name}} with an event handler:

  'click .WhisperCharacter'(event, template) {
    alert(this.name); //<- Wrong
  },

Normally, I'm able to retrieve the data with this.x on the {{each}} handlebar, but that only seems to work if I query whole documents each, not with an array inside one single document.

I tried a lot of funky stuff like this.lastWhisp.name etc. basically guessing. I can't get behind what it needs to retrieve the information of that {{each}} handlebar. Could someone help me out with how it works in this case?

Thank you!


Solution

  • The event itself has no information on the name, because it represents only that you have clicked a DOM element.

    To transport this value, you may use a data-* data attribute:

    {{#each name in chatMeta.lastWhisp}}
     <div class="WhisperCharacter" data-name="{{name}}">
      {{name}}  
     </div>
    {{/each}}
    

    you can then easily read the data attribute from the event using the builtin jQuery .data method on the event target:

    'click .WhisperCharacter'(event, template) {
      const $target = template.$(event.currentTarget)
      const name = $target.data('name')
      alert(name)
    },