[英]Requirejs: pass parameters when using data-main Entry Point
在我所有的項目中,我都使用以下方法在整個應用程序中處理js。 但是,我對將變量傳遞給js中的模塊的方式不滿意:我在html上聲明了它們,然后在模塊上盲目地使用了它們。
我發現的所有stackoverflow問題/答案都在談論不同的設置,而不是使用這種數據主入口點方法。
的index.html
<html>
<body>
<article class="row m-b-xxl settings" data-js="modules/home"></article>
<script>
var bar = 'foo';
</script>
<script src="require.js" data-main="main"></script>
</body>
</html>
main.js
require.config({
paths: {
'jquery': 'jquery.min',
'foundation': 'foundation.min'
},
shim: {
"foundation": {
deps: ['jquery'],
exports: 'Foundation'
}
}
});
// Load our app module 'main.js' and pass it to our definition function
requirejs(['app'], function (App) {
App.initialize();
});
app.js
// The base app
var widgetList = {};
define(['jquery', 'foundation' ], function ($, Foundation)
{
var initialize = function () {
// Set user agent
var doc = document.documentElement;
doc.setAttribute('data-useragent', navigator.userAgent);
// Do the widget loading
$('[data-js]').each(function () {
var scope = this;
requirejs([$(scope).data('js')], function (widget) {
var widgetDeclaration = new widget();
widgetDeclaration.init(scope);
widgetList[widgetDeclaration.name] = widgetDeclaration;
});
});
}
return {
initialize: initialize
};
}
);
模塊/ home.js
define(['jquery'], function ($) {
var Widget = function () {
};
Widget.prototype = {
name: 'Dashboard Home',
init: function (scope) {
"use strict";
console.log(bar);
};
return Widget;
});
那么如何正確地將配置參數傳遞給模塊呢?
我可以找到的最佳解決方案是更改requirejs的設置:
<script src="require.js"></script>
<script type="text/javascript">define('homeConfig', function () {var homeConfig = {};return homeConfig;});</script>
<script>requirejs(['main.js'], function () { /*load or init your app here */});</script>
homeConfig
的模塊,可以使用iside其他模塊:) 因此,最后我沒有使用數據主入口點,因為它不適合我的設置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.