How to get the parent template instance (of the current template)

前端 未结 5 2172
抹茶落季
抹茶落季 2020-12-03 10:55

Is there a clean way to get the parent template of the current template? Nothing is officially documented in Meteor\'s API. I\'m talking about the Blaze.TemplateInstan

5条回答
  •  误落风尘
    2020-12-03 11:45

    Is there a clean way to get the parent template of the current template?

    Currently, none that I know of, but this is supposed to happen sometime in the future as part of a planned "better API for designing reusable components" (this is discussed in the Meteor post 1.0 roadmap).

    For the moment, here is a workaround I'm using in my projects :

    // extend Blaze.View prototype to mimick jQuery's closest for views
    _.extend(Blaze.View.prototype,{
        closest:function(viewName){
            var view=this;
            while(view){
                if(view.name=="Template."+viewName){
                    return view;
                }
                view=view.parentView;
            }
            return null;
        }
    });
    
    // extend Blaze.TemplateInstance to expose added Blaze.View functionalities
    _.extend(Blaze.TemplateInstance.prototype,{
        closestInstance:function(viewName){
            var view=this.view.closest(viewName);
            return view?view.templateInstance():null;
        }
    });
    

    Note that this is only supporting named parent templates and supposed to work in the same fashion as jQuery closest to traverse parent views nodes from a child to the top-most template (body), searching for the appropriately named template.

    Once this extensions to Blaze have been registered somewhere in your client code, you can do stuff like this :

    HTML

    
    
    
    

    JS

    Template.parent.created=function(){
      this.backgroundColor=new ReactiveVar("green");
    };
    
    Template.parent.helpers({
      backgroundColor:function(){
        return Template.instance().backgroundColor.get();
      }
    });
    
    Template.child.events({
      "click button":function(event,template){
        var parent=template.closestInstance("parent");
        var backgroundColor=parent.backgroundColor.get();
        switch(backgroundColor){
          case "green":
            parent.backgroundColor.set("red");
            break;
          case "red":
            parent.backgroundColor.set("green");
            break;
        }
      }
    });
    

提交回复
热议问题