Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#each string in an array with blaze in Meteor

I have an array of usernames that I am rendering in a list like so:

{{#each contacts}}
<div class="name">{{this}}</div>
{{/each}}

This works just fine, but then I try to get the username from an event:

'click .name': function(e,t){
console.log(this)
}

I get this frustrating object String {0: "c", 1: "h", 2: "a", 3: "r", 4: "l", 5: "i", 6: "e", length: 7, [[PrimitiveValue]]: "charlie"} which makes it very challenging to do string comparisons with. Any ideas why this is even a problem or what to do about it?

like image 757
Chet Avatar asked Oct 01 '14 18:10

Chet


1 Answers

In general in Javascript, context has to be an object rather than a primitive (link). Presumably, contacts is just an array of strings, so within each div tag these strings are boxed (i.e. cast to a reference type, in this case the String object). That's what you're logging here - the String object, rather than your original primitive.

You have two options:

  1. if you use this.valueOf() it will give you the primitive string back.
  2. alternatively, consider making contacts an array of objects (like [{value: 'nameOne'}, ...]). That way, you can replace {{this}} with {{value}} and this in your event handler will give you back the object in the same format you supplied it.
like image 167
richsilv Avatar answered Oct 22 '22 20:10

richsilv