Custom Bindings with ko.applyBindingsToNode

2,297 views
Skip to first unread message

loved...@gmail.com

unread,
Sep 27, 2013, 4:52:26 AM9/27/13
to knock...@googlegroups.com
Hi Friends.
I need your help about CustomBindings using with applyBindingsToNode.
I have two controls.
CountryDropdown, StateDropdown. If the CountryDropdown change I want to update StateDropdown data Source. How Can I do it ?
Because In my application i want to make some reusable controls which  already have data source.

ko.bindingHandlers.stateDropdown = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var countryCode = ko.unwrap(allBindingsAccessor().countryCode),
            states = ko.observableArray(
              ko.utils.arrayFilter(States, function(item) {
                  return item.CountryCode = countryCode;
              })
            ),
            select = document.createElement("select");
       
        //add select to virtual element
        ko.virtualElements.insertAfter(element, select, null);
       
        //apply foreach binding to the newly created ul with the data that we passed to the binding
        ko.applyBindingsToNode(select, {
            options: states,
            optionsValue: 'Code',
            optionsText: 'Name',
            value: valueAccessor(),
            validationTooltip: valueAccessor()
        });
       
        //tell Knockout that we have already handled binding the children of this element
        return { controlsDescendantBindings: true };
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext){
        //Need Update virtual Node here ??? How
    }
}

Please take a look at my jsfiddle

Michael Best

unread,
Sep 30, 2013, 8:21:14 PM9/30/13
to knock...@googlegroups.com, loved...@gmail.com
You can use a ko.computed for the states:

var states = ko.computed(function() {
    var countryCode = ko.unwrap(allBindingsAccessor().countryCode);
    return ko.utils.arrayFilter(States, function(item) {
        return item.CountryCode == countryCode;
    })
});

http://jsfiddle.net/mbest/DCz5r/7/

When using Knockout 3.0, it's better to use the new ko.applyBindingAccessorsToNode function.


-- Michael

loved...@gmail.com

unread,
Sep 30, 2013, 9:02:09 PM9/30/13
to knock...@googlegroups.com, loved...@gmail.com
Hi Thanks very much for your help Micheal. It works well.
Reply all
Reply to author
Forward
0 new messages