Ted Nyberg
Ted Nyberg

Reputation: 7401

Knockout does not trigger afterRender if collection is empty

I have a Knockout template like the following, and everything works great including the myFunction event handler being invoked after the binding has completed - as long as the myItems collection has any elements.

When the view model has 0 elements in the myItems Collection, afterRender does not seem to fire.

<table>
    <tbody data-bind="template: { foreach: myItems, afterRender: myFunction }">
        <tr>
            <td data-bind="text: $someProperty"></td>
        </tr>
    </tbody>                    
</table>

Is there any other Knockout event that can be used to invoke some logic after the view model has been databound when there is no data?

I want to be able to determine when the template is rendered, regardless of whether it has any elements.

Thanks!

Upvotes: 0

Views: 524

Answers (2)

Ted Nyberg
Ted Nyberg

Reputation: 7401

I decided to simply modify the callback of the AJAX call to explicitly invoke the afterRender event handler (cleverly named afterRender):

FUNCTIONS.InvoiceList = function(target) {

    var self = this;

    self.target = target;

    self.invoices = ko.observableArray();

    self.afterRender = function() {
        $('.loading').hide();
    };

    $.getJSON("http://hostname/api/invoices", function (data) {
        self.invoices(data);

        // Invoke event handler even when there are no items
        if(data.length==0) {
           self.afterRender();
        }

    });
};

Upvotes: 1

RredCat
RredCat

Reputation: 5421

Template is rendered container for items from your collection. If you don't have any items in your collection so there nothing to render and 'afterRender' isn't fired - it is common sense.

Could you specify what do you want to implement in this event and I try to help with way to do it.

Upvotes: 0

Related Questions