Bind to simple array of strings
Asked Answered
V

2

72

If I want to bind a template to a plain old array of strings, what do I put in the ${??} expression?

I hope this snippet isn't too short so as to confuse:

<ul data-bind="template: { name: 'authorTemplate', foreach: authors }">
</ul>

where authors is simply ["a", "b", "c"]

<script type="text/x-jquery-tmpl" id="authorTemplate">
    <li>${what_do_I_put_here???}</li>
</script>

I've tried: val value this and this.toString(). The last two displayed [object Object] so I suspect I'm pretty close there.

Vivianne answered 30/8, 2011 at 19:30 Comment(0)
V
107

From the documentation, the answer is:

When using a template: ${$data}

When not using a template: $data

Vivianne answered 30/8, 2011 at 20:19 Comment(7)
An explanation of $data or links to documentation would help would be googlers.Assumptive
I can't seem to find that—I got this answer from their google group. Do you by chance have a link?Vivianne
Afraid not, but presume it is in the jQuery templates documentation, or else (if it is specific to knockoutjs) in the knockoujs docs.Assumptive
The foreach documentation has a relevant exampleMarienthal
If not using templates, it would be <ul data-bind='foreach: array'><li data-bind='text: $data'>...Clandestine
@Assumptive knockoutjs.com/documentation/click-binding.html Note 1: Passing a “current item” as a parameter to your handler functionWeir
Knockout binds arrays by calling toString() on each member and then doing .join(", ").Steppe
K
51

For unnamed array (JSON like: ["value1", "value2"]), it would be:

<ul data-bind="foreach: $root">
 <li data-bind="text: $data"></li>
</ul>

$root keyword does the trick.

Kraigkrait answered 4/2, 2013 at 20:12 Comment(2)
Yeah - the above code was for use with jQuery templates. Having ditched that long ago and went with the native knockout templates, this indeed how to do it.Vivianne
Actually, $root represents the object passed to ko.applyBindings. So this would only work if you did something like ko.applyBindings(["value1", "value2"], document.getElementById("MyValueList"));. If you're going to be binding anything else on the page, you would be better served having this as a named member on your viewmodel, or you could write the array to the binding like so: foreach: ["value1", "value2"]. See knockoutjs.com/documentation/binding-context.html for more info.Tedda

© 2022 - 2024 — McMap. All rights reserved.