敲除和可观察的阵列不匹配 [英] Knockout and observable array mismatch
问题描述
在viewmodel中考虑以下属性
Consider the following properties inside a viewmodel
self.allValues = ko.observableArray();
self.selectedValues = ko.observableArray();
在编辑时, selectedValues
包含来自的值数据库。问题出在这里: selectedValues
包含 allValues
中包含的元素,但它们不相同的情况。它们从属性值的角度来看是相同的,但实际上是不同的对象。
On edit, selectedValues
contains values coming from database. Here is the problem: selectedValues
contains elements than are included on allValues
, but they are not the same instances. They are the same from properties values point of view but are actually different objects.
这导致每次淘汰赛使用 indexOf
超过 allValues
使用 selectedValues
中的对象始终无法找到对象。
This causes that every time knockout uses indexOf
over allValues
using objects from selectedValues
always fails to find the object.
我正在使用
但无法检查此数组中包含的正确元素。已检查
绑定上的selectedValues
I'm using selectedValues
on a checked
binding but fails to check the correct elements included on this array.
<div class="vars-list" data-bind="foreach: allValues">
<input type="checkbox" data-bind="checkedValue: $data...(etc)
checked: selelectedValues" />
</div>
敲除是否有任何方法可以通过属性值而不是内存地址来匹配对象?
Is there any way for knockout to match objects by property values instead of memory address?
推荐答案
使用自定义绑定是一种方法。以下是使用比较函数的已检查
绑定的变体。
Using a custom binding is one way to go. Here's a variation of the checked
binding that uses a comparison function.
ko.bindingHandlers.checkedInArray = {
init: function (element, valueAccessor, allBindings) {
ko.utils.registerEventHandler(element, "click", function() {
var observable = valueAccessor(),
array = observable(),
checkedValue = allBindings.get('checkedValue'),
isChecked = element.checked,
comparer = allBindings.get('checkedComparer');
for (var i = 0, n = array.length;
i < n && !comparer(array[i], checkedValue);
++i) { }
if (!isChecked && i < n) {
observable.splice(i, 1);
} else if (isChecked && i == n) {
observable.push(checkedValue);
}
});
},
update: function (element, valueAccessor, allBindings) {
var array = valueAccessor()(),
checkedValue = allBindings.get('checkedValue'),
comparer = allBindings.get('checkedComparer');
for (var i = 0, n = array.length;
i < n && !comparer(array[i], checkedValue);
++i) { }
element.checked = (i < n);
}
};
jsFiddle: http://jsfiddle.net/mbest/4mET9/
jsFiddle: http://jsfiddle.net/mbest/4mET9/
这篇关于敲除和可观察的阵列不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!