knockout.jsknockout-templating

knockout template click event doesn't update the listener


I create a simple template that set the "selectedItem" when clicked. I also added a simple textbox that binds to the "selectedItem" method, but I can't get it to update when clicking on the template list.

HTML

<div data-bind="template: { name: 'address-template', foreach: addresses }"></div>

<input type="text" id="textBoxAddressLine1" name="textBoxAddressLine1Name" data-bind="value: selectedItem ? selectedItem.AddressLine1 : ''" />

<script type="text/html" id="address-template">
    <a href="#" data-bind="click: function() { viewModel.selectItem($data); }">
        <h4 >Suggested Address</h4>
        <p>
            <dl>
                <dt>Address line 1:</dt>
                <dd data-bind="text: AddressLine1"></dd>
                <dt>Address line 2:</dt>
                <dd data-bind="text: AddressLine2"></dd>
            </dl>
        </p>
    </a>
</script>

JS

viewModel = {
                addresses: ko.observableArray(),
                selectedItem: ko.observable(),
                selectItem: function (data) {
                    this.selectedItem = data;
                }
            };
viewModel.addresses = [{"AddressSuggestionId":"895528b3-b5a3-4dc8-966c-094ef74d88d2","AddressLine1":"111 Test street","AddressLine2":"Test address line 2"},{"AddressSuggestionId":"d149b694-6450-4d86-a441-1f41cee732dd","AddressLine1":"222 test street","AddressLine2":"test addresline2"}]

ko.applyBindings(viewModel);

Take a look at the test code: http://jsfiddle.net/patremb/7meN8/6/

Thank you for your help!

Patrick


Solution

  • Since selectedItem is an observable, you need to invoke it for accessing/changing it's data.

    Try this:

    <input type="text" id="textBoxAddressLine1" name="textBoxAddressLine1Name"
           data-bind="value: selectedItem() ? selectedItem().AddressLine1 : ''" />
    

    And in your ViewModel:

    selectItem: function(data) {
                this.selectedItem(data);
                }