我正在使用 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);
当我更改下拉列表值时。股票值(value)保持不变?
感谢任何帮助。
最佳答案
问题的出现是因为您正在将 stocks
变量重新分配给另一个可观察对象。
所以你首先要做的是:
this.stocks = ko.observable();
然后订阅这个可观察对象。但稍后你会:
this.stocks = ko.observableArray(filteredStocks);
这将 stocks
与另一个可观察对象相关联。订阅将针对原始可观察对象,即第一个任务中的那个。
请参阅此 fiddle 以获取更短的示例:http://jsfiddle.net/9nGQ9/2/
解决方案是替换 this.stocks = ko.observable();
使用 this.stocks = ko.observableArray();
并替换 this.stocks = ko.observableArray(filteredStocks);
使用 this.stocks(filteredStocks);
关于javascript - knockoutjs 订阅不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19886776/