knockout.js - 0 length ObserveableArray when accessed inside function -


i have model class few functions (methods) attached it. when @ length of observable array outside of functions length returned correctly. when @ observablearray inside function of modelclass returns 0. if access item inside observablearray index inside function returns correct item. why length 0?

    function modelview(data) {       var self = this;         self.items= ko.observablearray(data.items);       var test = self.items().length; //shows correct number       self.editrule = function (product) {         for(var i=0; i<self.items().length; i++)               //dosuff self.items().length 0         }     } 

i found work around adding additional property viewmodel so:

     self.itemslength = ko.observable(self.items().length); 

obviously actual issue more complicated loop doing compare of items against parameters passed in make sure somethings valid. self.items masterlist.

try using ko.utils.arrayforeach iterating on observablearray:

function modelview(data) {       var self = this;       self.items = ko.observablearray(data.items);       var test = self.items().length; //shows correct number       self.editrule = function () {           ko.utils.arrayforeach(self.items(), function(item){               if (item.name === "2"){                   // example                   console.log(self.items().length); //will 3                   self.items.remove(item);                   console.log(self.items().length); //will 2               }           });       }  }  var mydata = {     items : [{id: 0, name: "0"},{ id: 1, name: "1"}, {id: 2, name: "2"}] }  var mymodelview = new modelview(mydata); ko.applybindings(mymodelview); 

with html tested:

<ul data-bind="foreach: items">     <li data-bind="text: name"></li> </ul> <a href="#" data-bind="click: editrule">editrule</a> 

you can use vanilla loop if like: similar own attempt might have mistake somewhere else.

function modelview(data) {       var self = this;       self.items = ko.observablearray(data.items);       var test = self.items().length; //shows correct number       self.editrule = function () {           for(var =0; < self.items().length; i++){               if (self.items()[i].name === "2"){                   // example                   console.log(self.items().length); //will 3                   self.items.remove(self.items()[i]);                   console.log(self.items().length); //will 2               }           }       }  } 

Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

java.util.scanner - How to read and add only numbers to array from a text file -

iphone - Three second countdown in cocos2d -