Knockout value not being set in function

 ̄綄美尐妖づ 提交于 2019-12-25 07:55:55

问题


I am having a problem when trying to get self.material (an observable) to load a value from within a function. When trying to load the observable in the select with a value, it shows as undefined. data.materialNumber has a string value and self.materials loads correctly. Any help would be appreciated!

I'll try to include only the code needed...

My html:

<select class="materialSelect" data-placeholder="Choose Material..." 
                                data-bind="options: materials,
                            value: material,
                            optionsText: function (item) { return item.description }, 
                            optionsValue: function (item) { return item.materialNumber },
                            chosen: materials,
                            chosenOptions: { width: '250px', search_contains: true }"></select>

My js:

function Mrs() {

var self = this;


self.materials = ko.observableArray();
self.material = ko.observable("");


bom.hubs.mrs.server()
    .getMaterialsForAuthorizedPlants(lastSection)
    .done(function (data) {
        data.materials.unshift({});
        self.material(data.materialNumber);
        self.materials(data.materials);
    });
 };
(function (bom) {
    "use strict";

    bom.hubs.done(function() {
        ko.applyBindings(new Mrs());
    });

})(bom);

回答1:


TL;DR Assign self.materials before self.material


The options binding will attempt to synchronise the selected option with the value, but when you assign self.material there are NO options, so it resets the material value back to undefined.

When you then set self.materials, the options then rebuilds, but self.material is now undefined.

If you swap the assignments, then the select options will be available when the material observable is set.



来源:https://stackoverflow.com/questions/21682961/knockout-value-not-being-set-in-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!