【问题标题】:knockout computed not being updated淘汰赛计算未更新
【发布时间】:2013-05-14 20:43:09
【问题描述】:

我正在尝试创建一个计算出的 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>

【问题讨论】:

  • 你的模型在body标签里面吗...??
  • 是的,抱歉,我没有包含所有 HTML,只包含相应的 sn-p

标签: javascript knockout.js knockout-2.0


【解决方案1】:

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

即而不是:

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

简单地使用:

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

有关更多信息,请查看 observableArray 的 official documentation,尤其是 从 observableArray 读取信息Manipulating an observableArray 部分。

【讨论】:

  • 啊!谢谢,我错过了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-17
相关资源
最近更新 更多