Okky
Okky

Reputation: 10466

Knockout binding not working incase of inline editing

I was trying to create an inline editing with knockout.

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

Upvotes: 1

Views: 218

Answers (2)

Pablo Romeo
Pablo Romeo

Reputation: 11396

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.

Upvotes: 2

Catalin Sterian
Catalin Sterian

Reputation: 96

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());

Upvotes: 0

Related Questions