Guilherme Oderdenge
Guilherme Oderdenge

Reputation: 5001

Rendering template just after click

The goal

Render a template just after a click binding with KnockoutJS.

The scenario

There is a table on my application and each row of this table is an item. When I click on some item, I will display its details in another container.

I pass all necessary information about this item by parameter and I need to get this parameter as data on a template binding — how can I do this?

Illustrative details

Here's my trigger:

[...]
    <tr data-bind="click: showDetails"></tr>
[...]

When someone click on it, displays the following template:

<p data-bind="text: itemName"></p>

... within the following container:

<div class="details" 
     data-bind="template: {name: 'detailsTemplate',
                           data: ~should be the parameter (object)
                                  that "showDetails" sends~}">
</div>

The final DOM should be the following and have to be visible just if I clicked on some item:

<div class="details" [...]>
    <p>Microsoft</p>
</div>

Someone knows how can I do this?

Upvotes: 2

Views: 97

Answers (1)

Kyeotic
Kyeotic

Reputation: 19867

In a master detail view, a very common practice is to have a "selected" item that the detail view will bind against.

Setting this selectedItem from a binding is made easier by the fact that the default parameter sent to functions in a click binding is the current binding context, which is the current item in a foreach binding. Couple this with the fact that observable are functions, you can set the selectedItem directly like this:

data-bind="click: $parent.selectedItem"

Then all you have to do is bind some detail view against the selectedItem. Take a look at this fiddle for a simple example.

Upvotes: 1

Related Questions