簡體   English   中英

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 ,會渲染布局,因為也會在控制台上打印“ all ready”消息,所以還會加載googleAPI,fancyInput和geocomplete庫,並且也加載了landing.js(因為它加載了背景圖片和消息“ Meteor.isClient”也會被打印出來)。

但是然后,“着陸”模板永遠不會被渲染。 它的內容不會出現,並且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之前。 多奇怪!

我不明白為什么未加載模板,因為流星控制台上沒有出現錯誤。 任何想法?

編輯:如果我刪除布局,它確實起作用,如下所示:

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

這種布局有什么問題?

因此,我認為您可能對此有點想過。 為什么不將現有軟件包用於這些庫? 除了易於使用之外,某些第三方代碼會縮小到主應用程序js文件中,而不是發出其他HTTP請求來下載它們。

例如, dburles:google-maps會為您提供Google Maps API和您選擇的其他庫(可以選擇僅在特定路線上加載),而jeremy:geocomplete則為您提供Geocomplete(它將自動安裝該地圖包作為依賴項)。 有關實現,請參見jeremy:geocomplete 自述文件

至於Fancy Input,為什么不為此創建一個簡單的Meteor包包裝器,以便僅通過Meteor meteor add fancy-input呢?

另外,您的Template.landing.rendered回調不應位於onBeforeAction 理想情況下,它應該與登陸模板的其他代碼一起存在於自己的文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM