Why can't we call form () before applyBindings ()?

When we use knockout with UniformJS and call .uniform()

before ko.applyBindings

, the code below doesn't work?

HTML code:

<div id="myContainer">
    <div data-bind="foreach: teste">
        <input type="checkbox" value="" /> My checkbox
    </div>
</div>

      

Javascript code:

$("input").uniform();    // Call here... does not work!
function vm() {
    var that = this;

        this.teste = ko.observableArray([
            { id: 1, 'value': '1' },
            { id: 2, 'value': '2' },
            { id: 3, 'value': '3' },
        ]);    
}

ko.applyBindings(vm());
//$("input").uniform();    // Call here... works fine!!!

      

However, if we name it after ko.applyBindings

, everything works fine. Why is this?

See the question live on this JSFiddle .

+3


source to share


1 answer


Knockout dynamically creates input

and adds them to the DOM. A single plugin can only work with existing elements. If you call .uniform()

on $("input")

before applyBindings, there is no input

s: the only input on the page is the template for the three inputs that are generated by KO.

I suggest you use a custom binding handler to accomplish this task:

ko.bindingHandlers.uniform = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        $(element).uniform();
    }
};

      

It can be used like this:

<input type="checkbox" value="" data-bind="uniform" /> My checkbox

      

You can also change the binding to take more parameters and start calling it like this:



<input type="checkbox" value="" data-bind="uniform: { wrapperClass: 'myClass' }" /> 

      

Here's a proof of concept , although you should also check this answer for a more robust implementation of options like binding.

The added benefit of all of this would be that you can drive consistent behavior from your view models, which in turn makes everything more testable.


PS. One option that might also be applicable is to use the templateafterRender

anchor bit .

+3


source







All Articles