1

我正在尝试创建一个计算出的 observable 并将其显示在页面上,我以前也这样做过,但我开始怀疑淘汰赛是否发生了变化——除了对 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>
4

1 回答 1

1

您在内部数组上调用push方法,而不是在 observableArray 包装器上,因此永远不会通知更改。

即代替:

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

简单地使用:

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

有关更多信息,请查看 observableArray 的官方文档,尤其是从 observableArray 中读取信息操作 observableArray部分。

于 2013-05-14T12:43:09.380 回答