簡體   English   中英

計算的淘汰賽未更新

[英]knockout computed not being updated

我正在嘗試創建一個可計算的可觀察對象並將其顯示在頁面上,並且我以前已經這樣做過,但是我開始懷疑剔除是否已更改-除了對totalAmount的綁定以外,其他所有操作都正常-由於某些原因,它永遠不會更改。 。有任何想法嗎?

我的模型如下:

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 is item1 text',image:'images/products/items/item1.png',price:15.99,id:1},
    {title:'item2',text:'this is item2 text',image:'images/products/items/item2.png',price:25.99,id:2},
    {title:'item3',text:'this is item3 text',image:'images/products/items/item3.png',price:55.99,id:3},
    {title:'item4',text:'this is 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);

這是關聯的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>

您在內部數組上而不是在observableArray包裝器上調用push方法,因此永遠不會通知更改。

即代替:

cartModel.cart().push(new cartItem(this));

簡單使用:

cartModel.cart.push(new cartItem(this));

有關更多信息,請參閱observableArray的官方文檔 ,尤其是從observableArray讀取信息操作observableArray部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM