I am using knockoutjs
and I am new to it. I want to change the model data based on dropdown list selected value. So in my AppModel, I am subscribing the array that i want to change. But it is not working?. Here is my code:
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);
when i change the drop down list value. The stocks value remain the same ?
Any Help is appreciated.
The problem appears because you are reassigning the stocks
variable to another observable.
So you first do:
this.stocks = ko.observable();
And then subscribe to this observable. But later you do:
this.stocks = ko.observableArray(filteredStocks);
This associates stocks
with another observable. The subscription will be for the original observable, the one from the first assignment.
See this fiddle for a shorter example: http://jsfiddle.net/9nGQ9/2/
The solution would be to replace this.stocks = ko.observable();
with this.stocks = ko.observableArray();
And replace this.stocks = ko.observableArray(filteredStocks);
with this.stocks(filteredStocks);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With