4

我正在使用knockoutjs,我是新手。我想根据下拉列表选择的值更改模型数据。所以在我的 AppModel 中,我订阅了我想要更改的数组。但它不工作?这是我的代码:

var filteredStocks  = [];
function viewModel(model) {
        this.isGeneral = ko.observable(model.generalStockEnabled);
        this.stocks = ko.observable();;
        if (model.generalStockEnabled === true)
        {
            filteredStocks = $.grep(model.stocks, function (v) {
                return v.sourceID === -1;
            });
        }
        else
        {
            filteredStocks = $.grep(model.stocks, function (v) {
                return v.sourceID !== -1;
            });
        }
        // If drop downlist changed
        var dropDownListSelectedValue = $('#enableGeneratInventorydl :selected').val();
        this.stocks.subscribe(function () {
            if (dropDownListSelectedValue === "True") {
                filteredStocks = $.grep(model.stocks, function (v) {
                    return v.sourceID === -1;
                });
                this.stocks(filteredStocks)
                this.isGeneral(true);
            }
            else
            {
                filteredStocks = $.grep(model.stocks, function (v) {
                    return v.sourceID !== -1;
                });
                this.stocks(filteredStocks)
                this.isGeneral(false);
            }
        }, this);

        this.stocks = ko.observableArray(filteredStocks);

当我更改下拉列表值时。股票价值保持不变?

任何帮助表示赞赏。

4

1 回答 1

10

出现问题是因为您将stocks变量重新分配给另一个 observable。所以你首先要做:

this.stocks = ko.observable();

然后订阅这个 observable。但后来你这样做:

this.stocks = ko.observableArray(filteredStocks);

stocks与另一个 observable 相关联。订阅将用于原始 observable,即第一个作业中的那个。请参阅此小提琴以获取更短的示例:http: //jsfiddle.net/9nGQ9/2/

解决方案是更换this.stocks = ko.observable();

this.stocks = ko.observableArray();

并更换this.stocks = ko.observableArray(filteredStocks);

this.stocks(filteredStocks);

于 2013-11-10T09:44:31.707 回答