Typically what you would want to do is represent your "selected" item as an observable. Handlers hooked up through the event
/ click
binding receive the current data item as the first argument. This can be used to populate your "selected" observable directly.
So, it would be like:
var ContactModel = function() {
this.id = ko.observable();
this.name = ko.observable();
this.addresses= ko.observableArray();
this.selectedAddress = ko.observable();
};
Then, you can bind against it like:
<div class='container'>
<!-- ko foreach: addresses -->
<div class='addrs' data-bind="event: { dblclick: $parent.selectedAddress }">
<span class='id' data-bind="text: id"></span> :
<span class='dat1' data-bind="text: type"></span>
<span class='dat2' data-bind="text: address"></span>
</div>
<!-- /ko -->
</div>
Note that you could create a function called "selectAddress" on your contact model and populate selectedAddress
with the item passed as the first argument. However, since an observable is already a function and populates its value using the first argument passed to it, in the sample above I bound dblclick
directly against the observable.
Sample here: http://jsfiddle.net/rniemeyer/2DmUf/
Sample with a function rather than bound directly against an observable here: http://jsfiddle.net/rniemeyer/mDKGV/ (just to help make it clear)
A handy thing to do with a "selected" observable, is to use the with
binding around an area, so it will re-render whenever you change to a new selected item and protect against when the item is null.
<div class='contactInfo' data-bind="with: selectedAddress">
<input class='dat2' type='text' data-bind="value: address" />
</div>