2017-02-23 28 views
0

這是我在Require.js上的第一次嘗試,我試圖弄清楚如何使用jQuery插件,特別是應該管理我的SPA的history.js。下面的代碼位於main.js中,並且腳本運行,但我無法計算如何實際使用History.pushState(),State.getState()和其他插件方法。我在控制檯中不斷收到"getState is not a function"錯誤消息。require history.js插件

(function() { 
    requirejs.config(
    { 
     baseUrl: 'js', 
     paths: { 
      'jquery': 'vendor/jquery-1.11.2.min', 
      'history': 'history.js' 
     }, 
     shim: { 
      'history': { 
       deps: ["jquery"], 
       exports: 'History' 
      } 
     }, 
     map: { 
      '*': { 'jquery': 'jquery-private' }, 
      'jquery-private': { 'jquery': 'jquery' } 
     } 
    } 
    ); 

    define(["jquery"], function($) { 
     $(function() { 

      require(['history'], function(History){ 
       var 
       History = window.History, 
       State = History.getState(); 
      }); 

     }); 
    }); 

})(); 

jQuery的私人包含此代碼:

define(['jquery'], function (jq) { 
    return jq.noConflict(true); 
}); 

這一切到目前爲止,我已經得到了,因爲我只是想弄清楚的東西出來,成立了一個文件。我對exports: Historyrequire(['history])中的函數參數有一些疑問,但它可能是完全不同的。順便說一句,我已經在之前的項目中使用過歷史,所以我覺得我理解如何使用它,以防萬一您可能想知道。 :)

編輯:我使用history.js文件的壓縮/未壓縮版本。添加一條路徑並沒有改變一件事。無論有沒有它,我都可以在需要時看到在瀏覽器中加載的腳本。我仍然得到History.getState()不是一個函數錯誤。

謝謝。

+0

我很驚訝你沒有爲'history'一個'paths'設置。他們分發的多個文件中的哪一個是您加載的?當我看[這裏](https://github.com/browserstate/history.js/tree/master/scripts)時,我看到一大堆子目錄中有一堆文件。另外,如果你在調用'History.getState()'之前檢查'window.History',你會得到什麼? – Louis

+0

我正在使用(un)壓縮的history.js文件。我用這些信息編輯了原文。如果在調用History.getState()之前檢查它,我會得到一個History函數。 [鏈接](https://i.imgsafe.org/3f009d92d4.jpg) – skrunic

回答

0

您正在訪問歷史代碼,但路徑沒有定義

  require(['history'], function(History){ 

你需要添加歷史js文件如jQuery的路徑。

paths: { 
     'jquery': 'vendor/jquery-1.11.2.min', 
     'history' : '<path to js file>' 
    }, 

嘗試和jQuery一起加入歷史依賴

define(["jquery","history"], function($,History) { 

    var 
    History = window.History, 
    State = History.getState(); 

})(); 
+0

感謝您的回覆,但它似乎並不重要,因爲我可以通過網絡檢查器看到該文件已在瀏覽器中加載。仍然獲取History.getState()不是函數錯誤。 :/我編輯原始帖子與選項無論。 – skrunic