knockout.jsko-custom-binding

Pass custom binding's value to DOM element added in custom binding


I am trying to use knockoutjs custom binding to create a component. This might not be a good idea and if there are other way to do the same thing, I am open to alternatives.

The idea is to set a custom binding to an element so the element content get's filled based on the data passed to the binding.

For example (in jade template), I would write:

div(data-bind="keyValueEditor: $data.somePropertyHoldingSomeData")

And I have the following (simplified for the question) custom binding:

ko.bindingHandlers.keyValueEditor = {
    init: function ( element, valueAccessor ) {
        var value = valueAccessor();

        var valueUnwrapped = ko.unwrap( value );

        $( "<span data-bind='text: theDataThatWasPassedToTheBinding.value'/>" ).appendTo( element );
        }
    },
    update: function ( element, valueAccessor ) {
    }
};

Here value is an observable that I would like to bind to the span content using the text binding. My problem is that I don't know what to put in theDataThatWasPassedToTheBinding so it equals to $data.somePropertyHoldingSomeData that was passed as the binding's value.

I tried:

$( "<span data-bind='text: " + valueAccessor().value + "'/>" ).appendTo( element );

and

$( "<span data-bind='text: " + ko.unwrap( valueAccessor() ).value + "'/>" ).appendTo( element );

Is this possible?


Solution

  • You can use function
    ko.applyBindingsToNode(node, bindings, viewModel, bindingAttributeName)

    ko.bindingHandlers.keyValueEditor = {
        init: function ( element, valueAccessor ) 
        {
            var somePropertyHoldingSomeData = valueAccessor();
            var span = $( "<span>" );
            span.appendTo(element);
            ko.applyBindingsToNode(span[0], {text: somePropertyHoldingSomeData.value})
        }
    }  
    

    JSFiddle DEMO