user373455
user373455

Reputation: 13271

Observable not updating when entering input field

I have the following typescript code:

///<reference path="typings/jquery/jquery.d.ts" />
///<reference path="typings/knockout/knockout.d.ts" />
///<reference path="typings/bootstrap/bootstrap.d.ts" />
///<reference path="typings/knockout.mapping/knockout.mapping.d.ts" />

class Municipality {
    id: KnockoutObservable<number>;
    name: KnockoutObservable<string>;

    constructor(
            id: number,
            name: string) {

        this.id = ko.observable(id);
        this.name = ko.observable(name);
    }
}

class SettingsViewModel {
    public municipality: KnockoutObservable<Municipality>;

    constructor() {
        this.municipality = ko.observable(new Municipality(0, ""));
    }

    editName = function (item) {
        $('#editValueDialog').modal('show');
    }

    submitUpdate = function () {
        var data = ko.mapping.toJSON(this.municipality());
        console.log(data);
    };
}

$(document).ready(function () {
    var serverData = JSON.parse($("#serverJSON").val());
    console.log(serverData);
    vm.municipality(new Municipality(serverData.Id, serverData.Name));
});

var vm: SettingsViewModel;
vm = new SettingsViewModel();
ko.applyBindings(vm);

In my view, I'm trying to just have a simple input-field:

<input type="text" data-bind="value: vm.municipality().name()">

The value of name is visible in the input-field, but when changing it, and triggering the submitUpdate event, the value hasn't changed, nor does it change when I check the attribute in the console.

if I enter:

vm.municipality().name('test') 

in the console the value changes.

What am I missing?

Upvotes: 1

Views: 170

Answers (2)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220884

submitUpdate = function () {
    var data = ko.mapping.toJSON(this.municipality());
    console.log(data);
};

Use an arrow function here -- the this value here is likely wrong at runtime when submitUpdate is triggered:

submitUpdate = () => {
    var data = ko.mapping.toJSON(this.municipality());
    console.log(data);
};

Upvotes: 1

Michael Crook
Michael Crook

Reputation: 1535

Quick fix would be to use vm.municipality().name.valueHasMutated() but it kinda looks like the binding has gone wrong somwhere.. .Maybe put the input field within a with bindings context so you can make somthing like this:

<!-- ko with: vm.municipality -->
    <input type="text" data-bind="value: name">
<!-- /ko -->

Don't know if this code will work, sorry no TS compiler and I don't have the time to convert your code to vanilla JS.

Hope some of this helps

Upvotes: 1

Related Questions