Iron Router:在渲染模板后加载 js 脚本

Iron Router: Load js script after template has been rendered

我正在尝试在 Iron Router 呈现模板后加载 javascript 文件(使用 IRLibloader):

Router.configure({
  layoutTemplate: 'layout',
  loadingTemplate: 'loading',
});

Router.route('/', {
  name: 'landing',
  template: 'landing',
  onBeforeAction: function () {
    var googleAPI = IRLibLoader.load('http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false');
    var fancyInput = IRLibLoader.load('/js/fancyInput.js');
    var geoComplete;
    if(googleAPI.ready()){
      geoComplete = IRLibLoader.load('/js/jquery.geocomplete.min.js');
    }

    if(googleAPI.ready() &&
       fancyInput.ready() &&
       geoComplete.ready()){
      console.log('All ready');
      this.next(); // Render the page when all the libraries are ready

      // Testing this here
      if(Meteor.isClient){
        console.log("Meteor.isClient");
        IRLibLoader.load('/js/landing.js');
        // Set places autocomplete
        Template.landing.rendered = function(){
          $('section :input').val('').fancyInput()[0].focus();
          $('section :input').geocomplete();
          console.log("loading.js ejecutandose (after render)");
        }
      }
    }
  }
});

但是当我浏览 localhost:3000 时,布局得到呈现,googleAPI、fancyInput 和 geocomplete 库也被加载,因为 'all ready' 消息在控制台打印,landing.js 也被加载(因为它加载了背景图像并且消息 'Meteor.isClient' 也被打印)。

但是,'landing' 模板永远不会呈现。它的内容不会出现,并且 Template.landing.rendered 中的控制台消息永远不会被打印出来。这是 template.js 文件:

<template name="landing">
  <img id='logo' src="img/logos/logo.png">
  <div id='content'>
    <section class='input'>
      <div>
        <input type='text' placeholder='Type text here'>
      </div>
    </section>
  </div>
</template>

我还尝试使用 onAfterAction 加载 landing.js,根据 Firebug 控制台,这似乎发生在 onBeforeAction 之前。好奇怪!

我不明白为什么没有加载模板,因为 meteor 控制台没有出现错误。有什么想法吗?

编辑:如果我删除布局,它确实有效,如下所示:

<template name="layout">
  <head>
    <title>Welcome to my app</title>
  </head>
</template>

这个布局有什么问题?

所以,我认为您可能有点想多了。为什么不为这些库使用现有的包?除了更易于使用之外,部分第 3 方代码将被缩小到主应用程序 js 文件中,而不是发出额外的 HTTP 请求来下载它们。

例如dburles:google-maps gets you the Google Maps API and extra libs of your choice (with the option to only load on specific routes) and jeremy:geocomplete gets you Geocomplete (which automatically installs that maps package as a dependency). See the jeremy:geocomplete README执行。

至于花式输入,为什么不 create a simple Meteor package 包装器,这样您就可以 meteor add fancy-input

此外,您的 Template.landing.rendered 回调不应该在 onBeforeAction 中。理想情况下,它应该与着陆模板的其他代码放在自己的文件中。