简体   繁体   中英

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.

Looking for some help!.

Thanks in advance.

after reading knockout.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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