淘汰赛 - 交叉输入绑定/可观察

时间:2016-10-06 19:44:35

标签: data-binding observable knockout-3.0

我想创建一个可观察的绑定,就像图像调整大小计算一样。经过几天尝试自己完成它我感到沮丧。也许有人可以帮助我。 视图有两个带数字的输入字段。让我们说第一个800和第二个600.当我更改第一个输入字段中的数字时,第二个也应该更新,但计算比例调整大小。因此,对于此任务,我需要来自第一个输入字段的旧值和新值,并使用第二个输入字段中的值进行计算。然后结果应传递给第二个输入字段。这应该也适用于vista verca。

编辑:经过一段距离后,我想我找到了一个有效的解决方案。下面我发布代码,以便当有人提出改进建议时,欢迎您:

// View has custom binding handler 'dimensionBinding' bound to an observable. Additional it put the contrary observable to the allBindings object.
 <input data-bind="dimensionBinding: valueHeight, contrary: valueWidth" type="number" >
 <input data-bind="dimensionBinding: valueWidth, contrary: valueHeight" type="number" >

    // viewModel
        self.valueHeight = ko.observable(800);
        self.valueWidth = ko.observable(600);

    // bindingHandlers
    ko.bindingHandlers.dimensionBinding = {
        init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {

// get the initially value from the observable and put it into the view        
$(element).val( ko.unwrap(valueAccessor()) );
        $(element).on('change', function(event) {
            // get the value from the contrary input field
            const contraryValue = ko.unwrap(allBindings.get('contrary')); 
            // get the value from this input before change
            const valueBeforeChange = ko.unwrap(valueAccessor()); 
            // get the new value from this input field
            const newValue = event.target.value; 
            // calc proportional and set the returning value to the contrary observable
            allBindings.get('contrary')( contraryValue / valueBeforeChange * newValue)
            valueAccessor()(newValue)    
        });
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        const value = ko.unwrap(valueAccessor());
        // update the view
        $(element).val(value);
    }
};

0 个答案:

没有答案