Search code examples
meteormeteor-blaze

What is 'Template.instance().view'?


I read [Template.instance().view]1 at Blaze docs.

Also I read Blaze.view().

I even saw the view object in the console log.

But I can't understand.

Could anyone explain it more intuitively and smoothly, please? :)


Solution

  • If you want to understand Views more deeply, you need to understand the relationship between Templates, TemplateInstances, and Views. Views are just reactive parts of the DOM. Template instances contain one View, but templates can create more views through functions that create renderable content like Blaze.with ({{#with}}) or Blaze.if ({{#if}}). These "child" views will will then store a parent pointer, which you can use to reconstruct the View tree.

    What might help your understanding is playing around with how Templates and Views interact in Chrome tools. You can find a template instance by using any DOM element. Here is an example to get you started:

    templateInstance = Blaze.findTemplate($('<some component in dom>')[0])
    view = templateInstance.view
    

    You can extend Blaze to contain findTemplate like this:

    Blaze.findTemplate = function(elementOrView) {
      if(elementOrView == undefined) {
        return;
      }
      let view = Object.getPrototypeOf(elementOrView) === Blaze.View.prototype
                  ? elementOrView
                  : Blaze.getView(elementOrView);
    
      while (view && view.templateInstance === undefined) {
        view = view.originalParentView || view.parentView;
      }
    
      if (!view) {
        return;
      }
    
      return Tracker.nonreactive(() => view.templateInstance());
    };