How do you get all instances of a Template?

2019-07-01 17:10发布

I know I can get a single template instance by doing Blaze.getView(node). But how can I find all instances of Template.foo?

1条回答
何必那么认真
2楼-- · 2019-07-01 17:35

If we borrow walkTheDOM from Crockford, we can drop this into the browser console and find all template instances on any page

function findAllTemplateInstances(templateName){
  function walkTheDOM(node, func) {
      func(node);
      node = node.firstChild;
      while (node) {
          walkTheDOM(node, func);
          node = node.nextSibling;
      }
  }
  var instances = [];
  walkTheDOM(document.body, function(node) {
    try{
      if (Blaze.getView(node).name === templateName){
        instances.push(Blaze.getView(node).templateInstance());
      }
    } catch(err){
    }
  });
  return _.uniq(instances)
}

Example using crater.io

查看更多
登录 后发表回答