简体   繁体   中英

save data in knockout.js

Help me please with knockout.js problem:

Why variable currentObject is undefinded ? How I can save current selected object in some variable ?

I have follow html view for down drop list:

 <select data-placeholder="Select object" class="span5" id="objects" data-bind="options: objects, optionsText: 'Name', optionsValue: 'Id', value: currentObject">
                    <option></option>
 </select>

ModelView:

function baseViewModel() {
    self.objects = ko.observableArray([]);

    ...

    self.currentObject = ko.observable();

    ...



    self.func = function() {

        //allert(self.objects()[0].Name) //return correct Name
        alert(self.currentObject().Name) //returns undefinded


    }

}

In your data-bind, you have value: currentObject which will indeed do a two-way bind between currentObject and the select's value .

The select's value is set to the Id field of the selected option's object (because of optionsValue: 'Id' in your data-bind). So, currentObject will be set to the Id field of the selected object, and that's why doing .Name gets you undefined.

I suggest not using optionsValue at all, this way KO will handle the value and it will be as if the value of the selectbox is the actual selected object, and value: currentObject will correctly set currentObject to the selected object. (And if you do want to use optionsValue , then know that currentObject will be set to the object's field, not the object itself)

Fiddle: http://jsfiddle.net/antishok/KXhem/78/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM