3

如果某些模块需要在页面中动态生成的 init 数据,我对如何构建基于 RequireJS 的项目的最佳方法感兴趣。

为了澄清,我的问题,我需要在主 html 页面的某个地方有这样的东西:

/* Following lines generated on server side so need to be in the html page*/
var initDataForModule1= [ data, generated, by, server];
var initDataForModule1= [ some, other, data, generated, by, server];

然后,我会有一些代码需要这些数据来完全设置 UI(不一定要加载)。例如,它们需要包含以下内容:

for(var i=0;i<initDataForModule1.length;i++)
     generateUIElementWithData(initDataForModule1[i]);

那么,我应该把上面的 UI 设置代码放在一个模块中,然后以某种方式加载它并给它初始化日期吗?或者哪个是一个好的方法?我在想类似的东西:

<script src="/js/lib/require.js"></script>
<script>
    var initDataForModule1= [ data, generated, by, server];
    var initDataForModule1= [ some, other, data, generated, by, server];

    require(['module1'], function(module1){
       module1.initWithData(initDataForModule1);
    });

    ...
<script>

另外,哪个是我的角色的好地方requirejs.config()

4

1 回答 1

1

Rendering JavaScript from server-side is asking for trouble: mixing languages makes it nearly impossible to refactor as you'll end up with templating tags in your JS files (that will also flag up during validation/linting). It would also couple your front- and back-end code, making the project less portable.


I decided to use the "text" plugin which makes an AJAX call and reads config at runtime (you'll need to remember to set inlineText to false in your r.js buildconfig file), for example:

require(['main', 'someDep', 'text!../ajax/config'],
        function(App, someDep, configString) {
    App.start(dep, JSON.parse(configString);
});

Where "../ajax/config" is the path to a URL that serves the config in JSON format(*).

(*) There is also the JSON plugin but I couldn't get it to work and parsing JSON text "manually" wasn't much of a hassle for me.

于 2013-11-12T15:22:04.810 回答