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?
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:
this.valueOf()
it will give you the primitive string back.[{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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With