meteormeteor-blaze

Meteor.js onRendered not triggered for dynamic template on data change


I'm trying to integrate a dynamic template called "page-event" on "page-main" which depends on data from a helper:

HTML MAIN

{{>Template.dynamic template="page-event" data=selectedEvent}}

JS MAIN

Template["page-main"].helpers({
    selectedEvent: function() {
        var eventId = Template.instance().selectedEventId.get()
        event = Collections.Events.findOne(eventId);
        return { event: event };
    }
});

JS EVENT

Template["page-event"].onRendered(function() {
        const ti = this;
        var eventData = this.data.event;
        console.log("RENDERING EVENT");
        // Color picker
        var colorPicker = $(ti.find(".colorSelect"));
        colorPicker.colorpicker({ format: "hex" });
        colorPicker.colorpicker("setValue", eventData.color);
        colorPicker.colorpicker().on("hidePicker.colorpicker", function(event) {
            var rgb = event.color.toRGB();
            Meteor.call("setEventVsColor", eventData._id, "rgb(" + rgb.r.toString() + "," + rgb.g.toString() + "," + rgb.b.toString() + ")");
        });
});

JS EVENT (incl. Jankapunkt's solution)

    Template["page-event"].onRendered(function() {
            const ti = this;
            const data = Template.currentData()
            var eventData = data.event;
            ti.autorun( function() {
              console.log("RENDERING EVENT");
              // Color picker
              var colorPicker = $(ti.find(".colorSelect"));
              colorPicker.colorpicker({ format: "hex" });
              colorPicker.colorpicker("setValue", eventData.color);
              colorPicker.colorpicker().on("hidePicker.colorpicker", function(event) {
                var rgb = event.color.toRGB();
                Meteor.call("setEventVsColor", eventData._id, "rgb(" + rgb.r.toString() + "," + rgb.g.toString() + "," + rgb.b.toString() + ")");
            });
        });
    });

Whenever the data retrieved by the helper is modified, I expect the template to re-render, since some of the onRendered functionality (excluded in this example) depends on the new data. But onRendered never triggers. What am I doing wrong?

Edit: After using Jankapunkt's solution, some of the onRendered components trigger for every one of the parent template's collection items, not just the item passed to the child template.


Solution

  • You can check for reactive data updates using Template.currentData() within an autorun (Tracker) computation:

    Template["page-event"].onRendered(function() {
      const instance = this
      instance.autorun(() => {
        const data = Template.currentData() // reactive data source
        // ... process data
      })
    });
    

    According to the BlazeJS documentation it should work for onCreated, as well as onRendered