Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout JS event for any viewmodel dom update

I need to run a jquery ui bit of code whenever the DOM is updated via Knockout.JS. I realize this can be done using custom bindings, but that appears to be related to a specific viewmodel, I want to do it globally so whenever it happens on any viewmodel it fires?

Lets say I ALWAYS want a JQuery datepicker on all textboxes with class 'needsdate', rather than add this to each of my view models, it would be great if I could do it globally.

Is this possible?

like image 357
RodH257 Avatar asked Feb 08 '12 00:02

RodH257


1 Answers

If you are not going to be dynamically adding/removing elements, then you could just wire them up as normal. However, if you are working with dynamic content (like using an observableArray that is having its items modified), then you have a couple of options:

1- Like the answer here, you can create a custom binding. If you don't want to bind the value to a property on your view model, then you can simplify the binding to something like:

ko.bindingHandlers.datepicker = {
    init: function(element, valueAccessor) {
        //initialize datepicker with some optional options
        var options = ko.utils.unwrapObservable(valueAccessor());
        $(element).datepicker(options);

        //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
            $(element).datepicker("destroy");
        });
    }
}; 

You would place it on an element like:

<input data-bind="datepicker: { minDate: new Date() }" />

2- the other option is to use the afterRender functionality of the template (and foreach which uses template) to wire up your datepickers after new content is rendered.

like image 83
RP Niemeyer Avatar answered Oct 08 '22 23:10

RP Niemeyer