dhysong
dhysong

Reputation: 1021

How to add an afterRender to a data-bind="with:

I need to add an afterRender callback to an existing data-bind statement, but I'm struggling with the syntax.

Here's the code I need to add the afterRender to, which currently renders correctly:

    <div data-bind="with: detail">
        <div class="row">
            <div class="header">
                <span data-bind="html: headerMainSegment"></span>
                <span data-bind="text: headerSecondSegment"></span>
                <div data-bind="text: rollupSegment"></div>
            </div>
        </div>
    </div>

Here's what I have tried, but the content disappears:

    <div data-bind="with: { data: detail, afterRender: customCode }">
        <div class="row">
            <div class="header">
                <span data-bind="html: data.headerMainSegment"></span>
                <span data-bind="text: data.headerSecondSegment"></span>
                <div data-bind="text: data.rollupSegment"></div>
            </div>
        </div>
    </div>

I added the customCode method to the viewmodel, but all of the data attributes appear to be null when rendered.

Upvotes: 3

Views: 4781

Answers (1)

Michael Best
Michael Best

Reputation: 16688

If you want to use afterRender, you'll need to use the template binding instead.

<div data-bind="template: { data: detail, afterRender: customCode }">
   <div class="row">
        <div class="header">
            <span data-bind="html: headerMainSegment"></span>
            <span data-bind="text: headerSecondSegment"></span>
            <div data-bind="text: rollupSegment"></div>
        </div>
    </div>
</div>

Another option is to create a custom binding that does your "custom code" and have it run after the with binding:

<div data-bind="with: detail, customCode: detail">
    <!-- ... -->
</div>

The custom binding would be something like this:

ko.bindingHandlers.customCode = {
    update: function (element, valueAccessor, allBindings, vm, context) {
        ko.unwrap(valueAccessor());     // access the value so we're updated when it changes

        // do my custom code with the element... 
    }
};

Upvotes: 3

Related Questions