mbest / knockout-freedom

Frees each binding from being updated by updates to its siblings.
14 stars 0 forks source link

why not use a computed as the wrapped value? #2

Closed mbest closed 11 years ago

mbest commented 12 years ago

ko.bindingValueWrap currently wraps the binding value using a psuedo-observable function. It may seem like ko.computed would do the job just as well. That is actually true (mostly). The problem with using ko.computed here is that it needs to be disposed when the element is removed, but there's currently no way to get the element in ko.bindingValueWrap. This would change If/when SteveSanderson/knockout#474 is included in Knockout.

ko.bindingValueWrap using ko.computed and element:

ko.bindingValueWrap = function(element, valueAccessor, valueWriter) {
    var valueFunction = ko.computed({
        read: function() {
            return ko.utils.unwrapObservable(valueAccessor());
        },
        write: function(valueToWrite) {
            var value = valueAccessor();
            if (ko.isObservable(value)) {
                value(valueToWrite);
            } else if (valueWriter) {
                valueWriter(valueToWrite);
            }
        },
        disposeWhenNodeIsRemoved: element
    });
    ...
    return valueFunction;
};

Here's a version that could work right now, but doesn't dispose the computed until it's updated:

ko.bindingValueWrap = function(valueAccessor, valueWriter) {
    var valueFunction = ko.computed({
        read: function() {
            return ko.utils.unwrapObservable(valueAccessor());
        },
        write: function(valueToWrite) {
            var value = valueAccessor();
            if (ko.isObservable(value)) {
                value(valueToWrite);
            } else if (valueWriter) {
                valueWriter(valueToWrite);
            }
        },
        disposeWhen: function() {
            return !valueFunction.getSubscriptionsCount();
        }
    });
    ...
    return valueFunction;
};