Dojo require() and AMD (1.7)

允我心安 提交于 2019-12-03 02:07:15
Domenic

The dependency array format:

define(["a", "b", "c"], function (a, b, c) {
});

can indeed be annoying and error-prone. Matching up the array entries to function parameters is a real pain.

I prefer the require format ("Simplified CommonJS Wrapper"):

define(function (require) {
    var a = require("a");
    var b = require("b");
    var c = require("c");
});

This keeps your lines short and allows you to rearrange/delete/add lines without having to remember to change things in two places.

The latter format will not work on PS3 and older Opera mobile browsers, but hopefully you don't care.


As for why doing this instead of manually namespacing objects, @peller's answer gives a good overview of why modularity is a good thing, and my answer to a similar question talks about why AMD and module systems as a way of achieving modularity are a good thing.

The only thing I would add to @peller's answer is to expand on "paying attention to dependencies actually makes for much better code." If your module requires too many other modules, that's a bad sign! We have a loose rule in our 72K LOC JavaScript codebase that a module should be ~100 lines long and require between zero and four dependencies. It's served us well.

requirejs.org gives a pretty good overview of what AMD is and why you'd want to use it. Yes, Dojo is moving towards smaller modules which you would reference individually. The result is that you load less code, and your references to it are explicit. Paying attention to dependencies actually makes for much better code, I think. AMD enables optimizations, and once the migration is complete, you don't have to load everything into globals anymore. No more collisions! The require() block wraps the code which uses various modules. domReady! relates to the loading of the DOM and has nothing to do with variables being in scope.

Anyway, this is deviating from the Q&A format of SO. You might want to ask specific questions.

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