Skip to main content

Dojo require() and AMD (1.7)


I'm having a heckuva time transitioning to Dojo and the new AMD structure, and I'm really hoping someone can shed some light on the whole concept. I've been living on Google for the last few weeks trying to find information on not the usage, but the structure and design pattern trends in using this.



I find it strange that for a relatively complex javascript application, such as for a main page where Dijits need to be created and styled, DOM elements created, etc, that I need to require, and therefore use, a TON of different modules that were otherwise available in the dojo namespace before the AMD system (or, at least, not assigned to 23 different vars).



Example:




require(['dijit/form/ValidationTextBox', 'dijit/form/SimpleTextarea', 'dijit/form/CheckBox', 'dijit/Dialog', 'dijit/form/Form'])
require(['dojo/ready', 'dojo/parser', 'dojo/dom-style', 'dijit/registry', 'dojo/dom', 'dojo/_base/connect', 'dojo/dom-construct'],
function(ready, parser, style, registry, dom, event, construct){
//...etc
}



That's only a few of the modules for one of the pages I'm working on. Surely there's a better, non-breaking-in-future-releases way of accessing these methods, etc. I mean, do I really have to import an entirely new module to use byId() ? And yet another to connect events? On top of that, all the clutter being created by having to assign a variable name in the functions argument list to cling to just seems like such a backstep.



I thought maybe you would require() the module only when needed, such as the query module, but if I need it more than once, then chances are the variable it's assigned to is out of scope, and I'd need to put it in a domReady! or ready call. reaalllly....??!



Which is why I can only assume it's my lack of understanding for dojo.



I really have looked and searched and bought books (albeit, a pre-AMD one), but this library is really giving me a run for my money. I appreciate light anyone can shed on this.



Edit for Example




require(['dijit/form/ValidationTextBox'])
require(['dojo/ready', 'dojo/parser', 'dojo/dom-style', 'dijit/registry', 'dojo/dom', 'dojo/_base/connect', 'dojo/dom-construct'], function(ready, parser, style, registry, dom, event, construct){
/* perform some tasks */
var _name = new dijit.form.ValidationTextBox({
propercase : true,
tooltipPosition : ['above', 'after']
}, 'name')

/*
Let's say I want to use the query module in some places, i.e. here.
*/
require(['dojo/query', 'dojo/dom-attr'], function(query, attr){
query('#list li').forEach(function(li){
// do something with these
})
})
}



Based off of this format, which is used with many examples both from the dojo toolkit folks as well as third party sites, it would be, IMHO, absolutely ridiculous to load all the required modules as the first function(ready, parser, style, registy... would get longer and longer, and create problems with naming collisions, etc.



Firing up and require() ing all the modules I would need during the life of the script just seems silly to me. That being said, I'd have to look at some of the "package manager" scripts. But for this example, if I wanted to use the query module in select places, I would either have to load it up with the rest in the main require() statement. I understand why to an extent, but what's so bad with generic dot-syntax namespaces? dojo.whatever? dijit.findIt()? Why load module, reference in a unique name, pass through closure, blah blah?



I wish this were an easier question to ask, but I hope that makes sense.



Exasperation



Call me a newb, but this is really.. really.. driving me mad. I'm no noob when it comes to Javascript (apparently not) but wow. I cannot figure this out!



Here's what I'm gathering. In adder.js:




define('adder', function(require, exports){
exports.addTen = function(x){
return x + 10
}
})



In some master page or whatever:




require(['./js/cg/adder.js'])



...which doesn't follow the neat require(['cg/adder']) format but whatever. Not important right now.



Then, the use of adder should be:




console.log(adder.addTen(100)) // 110



The closest I got was console.log(adder) returning 3 . Yep. 3 . Otherwise, it's adder is not defined .



Why does this have to be so difficult? I'm using my noob card on this, cause I really have no idea why this isn't coming together.



Thanks guys.


Source: Tips4allCCNA FINAL EXAM

Comments

  1. 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.

    ReplyDelete
  2. 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.

    ReplyDelete

Post a Comment

Popular posts from this blog

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex