未在功能中设置删除值 [英] Knockout value not being set in function

查看:81
本文介绍了未在功能中设置删除值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试获取self.material(可观察的)以从函数内加载值时遇到问题.当尝试使用值加载选择中的可观察对象时,它显示为未定义. data.materialNumber具有字符串值,并且self.materials正确加载.任何帮助将不胜感激!

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...

我的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>

我的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);

推荐答案

TL; DR在self.material之前分配self.materials

TL;DR Assign self.materials before self.material

选项绑定将尝试将所选选项与值同步,但是当您分配self.material时,没有选项,因此它将材质值重置为undefined.

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.

然后设置self.materials时,选项会重新生成,但是self.material现在未定义.

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.

这篇关于未在功能中设置删除值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆