1
votes

I have a question regarding the use of the knockout mapping plugin.

I'm fetching a simple array from the server and convert it into javascript objects using the mapping plugin. Since I want the properties on the items to be observable I'm supplying the pugin with a custom mapping for the create callback.

    var meeting = function (id, titel, description) {
        var self = this;
        self.Id = id;
        self.Titel = ko.observable(titel);
        self.Description = ko.observable(description);
        self.Test = ko.computed(function () { return self.Description(); });
        return self;
    }

    var mapping = {
        create: function (json) {
            return new meeting(json.data.Id, json.data.Titel, json.data.Description);
        }
    }

When I call the ko.mapping.fromJS(myFetchedData) I see (with debugger attached) the create-function being called for every item in my array. Everything is bound to the HTML controls fine. I see a li item appearing for every item in the array.

<ul id="meetings" data-bind=" foreach: meetings">
    <li class="ui-widget-content ui-corner-all">
        <h1 data-bind="text: Titel" class="ui-widget-header"></h1>
        <div>
            <input type="text" data-bind="text: $data.Description || 'Omschrijving?'"></input>,
        </div>
        <div>
            <input type="text" data-bind="text: $data.Test || 'Omschrijving?'"></input>,
        </div>
        <a href="#" data-bind="click: $root.updateMeeting" >Update</a>
        <a href="#" data-bind="click: $root.removeMeeting" >Remove</a></p>
    </li>
</ul>

However: the Description property does not seem to be Observable. Changing the value does not result in an updated value of the Test-computed property.

Am I missing something here?

Any help would be appreciated.

Full sample code can be found here: http://jsfiddle.net/dtiemstra/wRg88/

1

1 Answers

2
votes

You need to bind to the <input> control's value property - not its text property.

So instead of:

<input type="text" data-bind="text: $data.Description || 'Omschrijving?'"></input>

you should write:

<input type="text" data-bind="value: $data.Description || 'Omschrijving?'"></input>

See http://jsfiddle.net/wRg88/8/