fox
fox

Reputation: 181

Update view after setting to localstorage knockout

I want to push in array and set it localstorage in knockout. so far so good. as far as i want to retrieve data and push new data and show them into view. it's not working.

    var viewModel = function() {
    var self = this;
    this.tags = ko.observable('');
    self.tempNum = ko.observableArray();
    self.tempNum = localStorage.getItem('tags') ? JSON.parse(localStorage.getItem('tags')) : []; // this line wont let data to be updated
    self.formSubmit = function(){
        var self = this;
        var num = checknum(self.tags().split(/[,;\n]+/));
        console.log(self.tempNum)
        localStorage.setItem('tags',ko.toJSON(num));
    }
    self.removeTags = function() {
        console.log("ada")
    }

    function checknum(item){
        for(var i = 0; i < item.length; i++){
            if(!isNaN(item[i]) && item[i] != ''){

                if(item[i] >= 0){
                    self.tempNum.push({value:item[i],color:"red"})
                }else{
                    self.tempNum.push({value:item[i],color:"blue"})
                }

            }
        }
        return self.tempNum
    }

};

ko.applyBindings(new viewModel());

Actually everything is working , and when i add this line :

self.tempNum = localStorage.getItem('tags') ? JSON.parse(localStorage.getItem('tags')) : [];

view doesn't update. Any suggest ? Thank you

Upvotes: 0

Views: 211

Answers (1)

Faizan
Faizan

Reputation: 96

I don't have enough reputation to add a comment otherwise I would have asked for your html code in a comment first.

Without your html code it is hard to guess what you are trying to achieve but when you add this line

self.tempNum = localStorage.getItem('tags') ? JSON.parse(localStorage.getItem('tags')) : [];

to your code then you are replacing tempNum observable array with a plain javascript array so your associated view won't get updated.

Try replacing with this

self.tempNum(localStorage.getItem('tags') ? JSON.parse(localStorage.getItem('tags')) : []);

See if this helps

Upvotes: 1

Related Questions