2013-01-22 63 views
1

f.e.我有:requirejs再次執行require模塊

require(['module1'], function(module1_callback){ 
//callback_1 after code is loaded 
}); 

和module1.js

define(['module2'], function(module2_callback) 
{ 
    //function_1 to perform something 
    return 'something'; 
}); 

我需要點播模塊1,但我需要運行function_1每次我requre該模塊, 在模塊1這種情況下function_1僅在第一次執行負載,但我需要每次我需要module1的例程。只返回回調執行

回答

2

這不是requirejs工作的方式。但是你可以返回,將執行的東西,然後返回一些功能:

define(['module2'], function(module2_callback) { 
    return function() { 
    //to perform something 
    return 'something'; 
    } 
}); 

和你的基地模塊:

require(['module1'], function(module1_callback){ 
    var something = module1_callback(); 
}); 
-2

檢索功能,引入了更多的複雜性和它是不是在某些情況下與骨幹工作插件和特別是具有大1/1頁應用循環依賴,其中頁面的某些部分需要從頭開始重新初始化, 我endup使用魔法模塊

https://github.com/jrburke/requirejs/wiki/Differences-between-the-simplified-CommonJS-wrapper-and-standard-AMD-define#wiki-magic

undef

define(['module2', 'module'], function(module2_callback) { 
    //push module id into global array 
    window.undefArr.push(module); 
    //all code here will be executed on every require 
}); 

//before require undef modules 
//here you can control which modules undef which to leave in memory 
//based on module properties like path, name, status etc. 
_.each(window.undefArr, function(mod){ 
    requirejs.undef(mod.id); 
}); 
//init undefArr 
undefArr = []; 
require(['module1']); 
+0

這是否意味着,每一個未定義的模塊需要重新加載以及如何與編譯的模塊這項工作? –

+0

上下文將不會被再次加載,它將從緩存中取出,但只有文件上下文,如果你的模塊返回編譯的東西,它將被重新編譯,basiccaly它會在該模塊上再次執行eval –

+0

你的方法看起來有點過於複雜。僅僅爲模塊本身添加一個復位功能不是更容易。或者甚至更好的在你的模塊中有一個getter,爲你提供一個新的實例。 –