我正在尝试让我的自定义绑定既适用于可观察对象,也适用于普通对象。我遵循了这个问题的答案:
writeValueToProperty isn't available
但是,如果我在执行allBindingsAccessor时查看返回的对象,'_ko_property_writers‘属性是未定义的。
有没有人知道这一点在knockout的版本3中有没有改变?
编辑
对不起,我应该声明,我正试图以一种可观察到的不可知论的方式,将值写回模型。
发布于 2014-05-23 23:00:21
这对我很有帮助:
ko.expressionRewriting.twoWayBindings.numericValue = true;
ko.bindingHandlers.numericValue = {
...
} 它是在指定绑定为双向后定义的。所以我可以在我的自定义绑定中使用类似的东西:
ko.expressionRewriting.writeValueToProperty(underlying, allBindingsAccessor, 'numericValue', parseFloat(value)); writeValueToProperty在内部定义为:
writeValueToProperty: function(property, allBindings, key, value, checkIfDifferent) {
if (!property || !ko.isObservable(property)) {
var propWriters = allBindings.get('_ko_property_writers');
if (propWriters && propWriters[key])
propWriters[key](value);
} else if (ko.isWriteableObservable(property) && (!checkIfDifferent || property.peek() !== value)) {
property(value);
}
}发布于 2013-12-19 20:51:42
执行此操作的标准方法是使用如下所述的ko.unwrap:http://knockoutjs.com/documentation/custom-bindings.html
例如:
ko.bindingHandlers.slideVisible = {
update: function(element, valueAccessor, allBindings) {
// First get the latest data that we're bound to
var value = valueAccessor();
// Next, whether or not the supplied model property is observable, get its current value
var valueUnwrapped = ko.unwrap(value);
// Grab some more data from another binding property
var duration = allBindings.get('slideDuration') || 400; // 400ms is default duration unless otherwise specified
// Now manipulate the DOM element
if (valueUnwrapped == true)
$(element).slideDown(duration); // Make the element visible
else
$(element).slideUp(duration); // Make the element invisible
}
};在该示例中,无论用户绑定到可观察对象还是正常对象,valueUnwrapped都是正确的。
https://stackoverflow.com/questions/20682190
复制相似问题