Knockout master detail not working with select

2019-02-20 23:46发布

问题:

here`see my fiddle

http://jsfiddle.net/kirannandedkar/JUChh/2/

When i click on name it doesnt load up select list and gives errror that function is expected. Actually i want to load select and value should be selected . When i change something in select it should get reflected in the list. Currently ModuleId is not getting populated in list and when i click on list its not populating the select list.

ViewModel:

var Person = function(id, name, country,ModuleId) {
    var self = this;
    self.id = ko.observable(id);
    self.name = ko.observable(name);
    self.country = ko.observable(country); 
    self.ModuleId= ko.observable(ModuleId);
    return self;
};

var vm = (function() {
    var people = ko.observableArray(),
        selectedPerson = ko.observable();
        self.editModuleId = ko.observable();
        self.modules = ko.observableArray([{"Id": 1,"ModuleName": "M1"},{"Id":2,"ModuleName":"M2"}]);

        getPeople = function() {
            people.push(new Person(1, 'John', 'USA',1));
            people.push(new Person(2, 'Mike', 'UK',1));
            people.push(new Person(3, 'Dan', 'AUS',2));
        },
        selectPerson = function(p){
            selectedPerson(p);
             self.editModuleId(ko.utils.arrayFirst(self.modules(), function (data) {
                    console.log("item module id " + p.ModuleId());
                    return data.Id() === p.ModuleId();
                }));
        };



    getPeople();

    return {
        people: people,
        selectedPerson: selectedPerson,
        selectPerson : selectPerson 
    };
})();


ko.applyBindings(vm);

View:

<ul data-bind="foreach: people">
 <li data-bind="text:name, click:$parent.selectPerson"></li>
<li data-bind="text:$root.editModuleId,click:$parent.selectPerson"></li>

</ul>

<div data-bind="with:selectedPerson">
<span data-bind="text:id"></span>
<input data-bind="value:name"/>
    <input data-bind="value:country"/>
    <select data-bind = "options:$root.modules,value:$root.editModuleId,optionsText:'ModuleName'"/>
</div>

回答1:

Modules observable array contains simple js objects without observables so when accessing its properties you don't need to put (). Remove it from data.Id in selectPerson function:

selectPerson = function(p){
    selectedPerson(p);
     editModuleId(ko.utils.arrayFirst(modules(), function (data) {
            console.log("item module id " + p.ModuleId());
            return data.Id === p.ModuleId();
        }));
};

Here is working fiddle: http://jsfiddle.net/JUChh/3/

I look at your code closer and found that editModuleId is redundant. You have needed property inside selectedPerson object - ModuleId and should bind value of dropdown to it.

Here is refactored fiddle: http://jsfiddle.net/JUChh/18/



标签: knockout.js