Search code examples
meteormeteor-blazebootstrap-datepicker

Template.subscriptionsReady disables onRendered functionality


I am initializing datepickers and form validation in Template.templatename.OnRendered.

 $('#dateAccepted').datepicker({
    endDate: new Date(),
    todayBtn: true,
    todayHighlight: true,
    autoclose: true
});

I am doing subscriptions, collection queries etc in Template.templatename.onCreated.

Template.insertContract.onCreated(function () {
var self = this;
self.autorun(function() {
    self.subscribe('getContracts');
    self.subscribe('getSuppliers' ,function(){
        var suppliers = Supplier.find({}).fetch();
        var sOptions = createOptions('supplier','supplierName',suppliers, true);
        Session.set('supplierOptions', sOptions);
    });
    self.subscribe('getItems');
});

});

If I put Template.subscriptionsReady on my template, datepickers and form validations stop working. No error messages.


Solution

  • This question gets asked a lot, but admittedly it's hard to search for. This is a similiar question about rendering carousel items.

    Here's what's happening:

    1. Your template renders and onRendered gets called.
    2. Your subscription isn't ready yet, so the datepicker isn't rendered but the initialization code runs in (1) as if it had.
    3. Eventually the datepicker is rendered.

    One possible answer is to render the datepicker in a sub-template. In the sub-template's onRendered you can run the initialization code, as you can be guaranteed that it's in the DOM. See the answer to the aforementioned question for an example.