javascript - knockout computed not being updated -


i trying create computed observable , display on page, , have done way before starting wonder if knockout has changed - works except binding on totalamount - reason never changes...any ideas?

my model follows:

var cartitem = function(item){     this.itemname = item.title;     this.itemprice = item.price;     this.itemid = item.id;     this.count=0; } var cartmodel = {     self:this,     footers:ko.observablearray([{title:'item1',text:'this item1 text',image:'images/products/items/item1.png',price:15.99,id:1},     {title:'item2',text:'this item2 text',image:'images/products/items/item2.png',price:25.99,id:2},     {title:'item3',text:'this item3 text',image:'images/products/items/item3.png',price:55.99,id:3},     {title:'item4',text:'this item4 text',image:'images/products/items/item4.png',price:5.99,id:4},  ]), cart:ko.observablearray([]), addtocart:function(){ if(cartmodel.cart().length>0){         for(var i=0;i<cartmodel.cart().length;i++){             if(this.id==cartmodel.cart()[i].itemid){                 cartmodel.cart()[i].count += 1;             }             else{                 cartmodel.cart().push(new cartitem(this));             }         }     }else{         cartmodel.cart().push(new cartitem(this));     }     console.log(cartmodel.cart().length);   } } this.cartmodel.totalamount=ko.computed(function(){     return this.cart().length;     },this.cartmodel); ko.applybindings(cartmodel); 

and here associated html:

<div data-bind="template:{name:'footertemplate',foreach:cartmodel.footers}">     <script type="text/html" id="footertemplate">         <div class="row">             <span class="span2"><h3 data-bind="text: title"></h3></span>             <span class="span2"><img data-bind="attr:{src: image}"/></span>             <span class="span5" data-bind="text:text"></span>             <span class="span1" data-bind="text:price"></span>             <spand class="span2"><button data-bind="click:$parent.addtocart">add</button></span>         </div>     </script> </div> <div class="row">     <span class="span2" data-bind="text:totalamount"></span> </div> 

you calling push method on internal array, not on observablearray wrapper, changes never notified.

i.e. instead of:

cartmodel.cart().push(new cartitem(this)); 

use simply:

cartmodel.cart.push(new cartitem(this)); 

for more info take @ official documentation observablearray, , in particular @ reading information observablearray , manipulating observablearray sections.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -