#each string in an array with blaze in Meteor
Asked Answered
V

2

7

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?

Vizard answered 1/10, 2014 at 18:3 Comment(1)
Did you try this._idVanguard
L
12

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.
Laius answered 1/10, 2014 at 18:29 Comment(0)
A
9

I think when you use {{this}} in a template, and the underlying data is a string literal, it gets converted into a String object. For the purposes of string manipulation, you will see no difference (in fact literals get converted to objects behind the scenes when methods are called on them). However it looks weird when you write it to the console. You can just do: console.log(this.toString()); or console.log(String(this));.

Addiction answered 1/10, 2014 at 18:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.