require.js + backbone.js: How to structure modules that have an initialize function?

你。 提交于 2019-12-03 16:48:20

As discussed in the comments above, you can avoid having to explicitly reference the parameters of the function by looping over them using the arguments object inside the function body. So:

require(['module1', 'module2', 'module3', ..., 'moduleN'],
  function(module1, module2, module3, ..., moduleN) {
    var init = function() {
        module1.init();
        module2.init();
        module3.init();
        ...
        moduleN.init();
    };
    return {init: init};
});

Becomes:

require(['module1', 'module2', 'module3', ..., 'moduleN'],
  function() {
    var args = arguments;
    var init = function() {
        var module;
        for (module in args) {
            if (args.hasOwnProperty(module) && typeof module.init === 'function') {
                module.init.call(this);
            }
        }
    };
    return {init: init};
});

I added in a hasOwnProperty() check inside the for in loop because, for a number of reasons, it's good practice. Also, you'll see the explicit check for init being a function before attempting to call it.

The reason for var args = arguments is so you can reference it from the inner function - otherwise you would be referencing the arguments passed to init(), which is not what you want.

As and aside, on an architectural level, I think the project structure you've described works incredibly well - I use it on a lot of very big projects and it's never let me down. Require.js is awesome! :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!