Question

I was trying to create an inline editing with knockout.

  • I created both 'span' and 'input' for same field.
  • On click of span I hide the span and 'show' the 'input'.
  • But the change in the input is not reflection on the span.

My Html field

<td>
    <span data-bind="text: name" style="display: inline;">Furious Lizard</span> 
    <input data-bind="value: name" style="display: none;" type="text">
</td>

My code for inline

$('td').on('click', function () {
    var spanElement = $(this).find('span');
    $(this).find('span').hide();
    $(this).find('input').show().select().on('blur', function () {
        $(this).hide();
        spanElement.show();
    });
});

Why isn't the binding working?

JSFiddle

Was it helpful?

Solution

I believe the reason is that eventhough you are binding to an observableArray, the properties on your objects are not themselves observable, so when the property is altered other bound elements aren't notified of the change.

I have edited your sample: http://jsfiddle.net/879Pk/3/

There you can see that the first element in your data, instead of just being standard properties, they are observable as well:

{
    name: ko.observable("Well-Travelled Kitten"),
    model: ko.observable(352),
    price: 75.95
}

NOTE: I didn't modify the price since you use it below for calculations. For that to work you'd have to modify all prices to be observable, and then while computing actually call the observable (using parenthesis) in order to get the actual value.

In order to avoid having to manually create the observables for each property, Knockout has a plugin called "Mapping" (http://knockoutjs.com/documentation/plugins-mapping.html) which does exactly that, using the following syntax:

var viewModel = ko.mapping.fromJS(data);

Now, regarding your second JSFiddle, I have just made a few corrections: http://jsfiddle.net/879Pk/5/

When you were adding the element the properties on the new one weren't observable, and you were also missing the parenthesis when evaluating the price property.

OTHER TIPS

you want that the data writen in the input to be visible in the span element as text? $(this).find('span').html($(this).find('input').val());

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top