tusharmath
tusharmath

Reputation: 10992

Not able to update model from a drop down using knockout.js

I have this sample fiddle here - http://jsfiddle.net/pRteA/3/

The problem is that I have to show the 'Name' of the selected object in the drop down, in a span. I am some how not able to do this for the SelectedUser object only. I feel that this has something to do with being linked to the select html tag.

However, i am still able to update the user.place object with no problem at all. I can not find any major difference in the way the 2 objects have been initialized.

Also, note that the sampleUsers list is actually coming from the server as an Ajax request every time, that is why I have used the method described here - How to use knockout mapping?

JS:

    var sampleUsers = [{
        Name: 'a',
        Id: 1},
    {
        Name: 'b',
        Id: 2},
    {
        Name: 'c',
        Id: 3},
    {
        Name: 'd',
        Id: 4},
    {
        Name: 'e',
        Id: 5}];

    var userViewModel = {
        user: ko.mapping.fromJS({
            place: {
                country: undefined,
                continent: undefined
            },
            selectedUser: {
                Name: undefined,
                Id: undefined
            }

        }),
        userOptions: ko.mapping.fromJS([])

    }

ko.applyBindings(userViewModel);
ko.mapping.fromJS(sampleUsers, userViewModel.userOptions);​

HTML:

<div>
    <select data-bind="options: userOptions,  optionsText: 'Name', value: user.selectedUser" class="grey-border">
    </select>
</div>Update

<div>
    <span>Country</span>
    <input type='text' data-bind="value:user.place.country" />
    <span data-bind='text:user.place.country'/>
</div>    

<div>
    <span>Continent</span>
    <input type='text' data-bind="value:user.place.continent" />
    <span data-bind='text:user.place.continent'/>
</div>  

Upvotes: 1

Views: 178

Answers (1)

Kyeotic
Kyeotic

Reputation: 19847

You have several syntax errors, and are calling the mapping plugin improperly. I really think you might want to go through the tutorials again.

Here is your fixed fiddle.

  1. You modify the userOptions "array" after binding to it, meaning that at binding time it has no properties.
  2. Then, after binding, the properties wont be subscirbed to, since you changed the structure of the object.
  3. Your binding path for your span doesn't include the () needed to specify observables.
  4. Your selectedUser's properties declared inline, but still constructed through the mapping plugin. This is kind of wasteful. Minor gripe.

Upvotes: 2

Related Questions