Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockoutjs subscribe not working?

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.

like image 873
user123456 Avatar asked Jan 11 '23 22:01

user123456


1 Answers

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);

like image 131
pax162 Avatar answered Jan 22 '23 16:01

pax162