簡體   English   中英

Rails 3.2:如何將大型javascript文件拆分為許多“部分”?

[英]Rails 3.2: How do I split large javascript file into many “partials”?

使用Rails Asset Pipeline,我想知道如何將大型javascript文件拆分為許多不同的部分。

例如:

YUI().use('app', function(Y) {
    //*=require sub/file_a.js
    //*=require sub/file_b.js
    //*=require sub/file_c.js
    //*=require sub/file_d.js
});
// this obviously is not the answer & does not work.

這只是為了讓開發人員受益,因為它擁有看起來更整潔的JS File,而不是擁有完整YUI視圖和模型的龐大應用。

我已經嘗試過使用ERB來包含一個沒有運氣的文件。 資產管道中不提供渲染功能,因此也很困難。

有任何想法嗎?

最終結果仍將通過rake compile:assets:all進行編譯-因此只能在開發環境中使用。

charlysisto有一個正確的主意。

答案是使用Sprockets和YUI模塊作為視圖/模型。

//*=require_self
//*=require view/file_a.js
//*=require model/file_a.js
//*=require view/file_b.js
//*=require model/file_b.js
YUI().use('app','app-view-file-a','app-view-file-b','app-model-file-a','app-model-file-b', function(Y) {
    Y.FileApp = Y.Base.create('fileApp', Y.App, [], {
        views: {
            fileA: {type: 'FileAView'},
            fileB: {type: 'FileBView'}
        }
    }, {
        ATTRS: {
            root: {value: '/'}
        }
    });

    var app = new Y.FileApp({
        contentSelector: '#pjax-content',
        serverRouting: true,
        transitions: true,
        container: '#file-app',
        viewContainer: '#file-app-views'
    }).render().showContent('#pjax-content', {view: 'FileAView'});
});

在視圖和模型文件中,只需像創建普通YUI3模塊那樣創建它們即可:

YUI.add('app-view-file-a', function(Y) {
  Y.namespace('FileAView');
  FileAView = Y.Base.create('fileAView', Y.View, [], {
      template: Y.Handlebars.compile(Y.one('#file-a-template').getHTML())
  });
  Y.FileAView = FileAView;
},'0.1.0',{requires:['node','handlebars'], skinnable:false});

一開始,我實際上使File.read在JS中工作。 但是這種方法看起來很雜亂,在開發領域中效果不佳。 Rails從不知道要重新編譯“父” js文件,因為時間戳沒有變化。 如果您不使用YUI,則File.read解決方案可能適用於您-但我會尋找其他解決方案。 每當我對子模塊進行更改時,必須輸入一個新行並刪除它就很煩人。

根據部分的內容,您可以將它們continain的對象包裝在vars中,然后可以執行以下操作:

//*=require sub/file_a.js
//*=require sub/file_b.js
//*=require sub/file_c.js
//*=require sub/file_d.js

YUI().use('app', function(Y) {file_a + file_b ...})

不知道這是否適合您的情況,不知道部分中有什么以及YUI()。use.use需要什么樣的參數。

暫無
暫無

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

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