我正在使用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);
当我更改下拉列表值时。股票价值保持不变?
感谢任何帮助。
答案 0 :(得分:9)
出现问题是因为您将stocks
变量重新分配给另一个observable。
所以你先做:
this.stocks = ko.observable();
然后订阅此可观察对象。但后来你做了:
this.stocks = ko.observableArray(filteredStocks);
这会将stocks
与另一个观察者相关联。订阅将针对原始观察,即第一次分配的观察。
请参阅此小提琴,以获得更短的示例:http://jsfiddle.net/9nGQ9/2/
解决方案是替换this.stocks = ko.observable();
this.stocks = ko.observableArray();
并替换this.stocks = ko.observableArray(filteredStocks);
this.stocks(filteredStocks);