我正在使用 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
变量重新分配给另一个 observable。
所以你首先要做:
this.stocks = ko.observable();
然后订阅这个 observable。但后来你做:
this.stocks = ko.observableArray(filteredStocks);
这将
stocks
与另一个 observable 相关联。订阅将用于原始 observable,即第一个分配中的那个。请参阅此 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/