简体   繁体   English

敲除样式绑定不会在基础数据修改时更新

[英]Knockout style binding not updating on modification of underlying data

I have an array of objects that I am displaying using a template. 我有一个使用模板显示的对象数组。 The template contains a button that changes colors depending on whether or not that object exists in another array: 模板包含一个按钮,该按钮根据该对象是否存在于另一个数组中来更改颜色:

HTML code: HTML代码:

<button type="button" class="btn btn-default productButton" data-bind="click: $root.selectForCompare, style: { color: $root.isSelectedForCompare($data) ? 'blue' : 'black' }">
    <span class="glyphicon glyphicon-duplicate"></span><br />Compare
</button>

View Model code: 查看型号代码:

self.isSelectedForCompare = function (product) {
    return indexOfProduct(self.compareItems(), product) !== -1;
};
self.selectForCompare = function (product) {
    var i = indexOfProduct(self.compareItems(), product);
    if(i === -1){
        self.compareItems().push(product);
    } else {
        self.compareItems().splice(i,1);
    }
};

If the user clicks on the button, the item will be added or removed for the second array (depending on whether or not it already exists in that array). 如果用户单击按钮,则将为第二个数组添加或删除该项目(取决于该数组中是否已经存在)。

When the page renders it correctly calls the isSelectedForCompare(product) function for each of the objects which results in the correct colors being displayed. 页面呈现后,它会为每个对象正确调用isSelectedForCompare(product)函数,从而显示正确的颜色。 The problem is that when the user clicks on the button (and the color should change), isSelectedForCompare is not called again to calculate the new color and the button does not change. 问题在于,当用户单击按钮(并且颜色应该更改)时,不会再次调用isSelectedForCompare来计算新颜色,并且按钮也不会更改。

Clicking the button modifies the array used to compute isSelectedForCompare(product) , but it doesn't appear that Knockout sees that a reason to update the style binding. 单击该按钮可以修改用于计算isSelectedForCompare(product)的数组,但是Knockout似乎没有看到更新样式绑定的原因。

As soon as I posted this, I realized my mistake: I was calling the array modification functions not on the observableArray, but on the evaluated javascript array: 发布此消息后,我立即意识到了自己的错误:我不是在observableArray上而是在评估后的javascript数组上调用数组修改函数:

self.compareItems().push(product)
self.compareItems().splice(i,1);

Should be: 应该:

self.compareItems.push(product)
self.compareItems.splice(i,1);

This didn't give the framework a chance to notify any of the observableArray's subscribers that the data had changed. 这没有给框架一个机会来通知任何observableArray的订户数据已更改。 I've fixed my code and it is working correctly now. 我已经修复了代码,现在可以正常工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM