简体   繁体   English

在数据绑定中使用对象进行敲除绑定

[英]Knockout binding using object in data-bind

i was trying to figure a way to bind some values as object to an element 我试图找到一种方法来将某些值作为对象绑定到元素

It works if i do binding like this 如果我这样绑定就可以了

var viewModel = { 
    someObj: ko.observable(),
    textBox: { 
        value: ko.observable('val'),
        attr: { title: 'Test', placeholder: 'Test' },
        style: { width: '100px' }
    }
}

<input type="text" data-bind="value: textBox.value, attr: textBox.attr, style: textBox.style />

But is there any way to bind like this 但是有没有办法像这样绑定

<input type="text" data-bind="bindFrom: textBox" />

I tried to create a customBinding "bindFrom" using ko.bindingHandlers but dont know how to trigger these individual bindings manually. 我尝试使用ko.bindingHandlers创建一个customBinding“ bindFrom”,但不知道如何手动触发这些单独的绑定。

Looking for some help!. 寻求帮助!

Thanks in advance. 提前致谢。

after reading knockout.debug.js 在阅读了击倒.debug.js之后

i have created this custom binding 我已经创建了这个自定义绑定

ko.bindingHandlers.bindFrom = {
    init: function (element, valueAccessor, allBindings) {
        var value = ko.utils.unwrapObservable(valueAccessor()) || {};
        ko.utils.objectForEach(value, function (bindName, bindValue) {
            bindObj = ko.bindingHandlers[bindName];
            ko.utils.objectForEach(bindObj, function (type, fn) {
                if (typeof fn == 'function')
                    fn(element, function () { return bindValue }, allBindings);
            });
        });
    }
}; 

which is working fine like expected. 运行正常,如预期。

check it out at JSFiddle JSFiddle上查看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM