KnockoutJs v3 - _ko_property_writers = undefined

时间:2013-12-19 12:48:05

标签: javascript knockout.js

我正在尝试使用自定义绑定来处理observable和普通对象。我按照这个问题的答案:

writeValueToProperty isn't available

但是,如果我在执行allBindingsAccessor时查看返回的对象,则属性'_ko_property_writers'未定义。

有人知道在淘汰赛的第3版中这是否发生了变化?

修改

对不起,我应该说,我试图以一种可观察的不可知方式将值“写”回模型

2 个答案:

答案 0 :(得分:2)

这对我有帮助:

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);
    }
}

答案 1 :(得分:0)

执行此操作的标准方法是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都是正确的。