Thread:Pecoes/@comment-3562424-20120422041911/@comment-3508190-20120426042429

I tested your code and, well, nothing much happpened. It added a single icon to the toolbar but clicking on it had no effect. Probably because you forgot the = in this bit of HTML:

Something else jumped out at me though. We seem to be at very different points in our evolution as JavaScript coders. Your code looks very much like a traditional class in object-oriented languages. That's just not very JavaScript.

All your event handlers are hidden away in the HTML. That's not where they're supposed to be. They should be the core of your code - not the appendage. Because they're not flat. They have an order that can only be achieved through nesting them:

Do you see that there's a sequence to the events in this code? First the dialog is loaded and when the loading's finished it's attached to the document and when that's done the "open Dialog" button is initialized. How long it takes for the dialog to load is irrelevant. The button will not become clickable before it has something to do.

You probably also saw that I've used two functions which have no context but their own. There's absolutely no need for them to be part of a class or any other larger context beyond their needs. That's something else you don't do in your code. You don't throw around with functions as parameters as I do - or as jQuery expects you to do. That leads me to believe you haven't groked closures yet.

This video explains it decently - even though the guy's a huge dork :) (The following will make no sense, if you haven't watched the video.) He doesn't explicitly point it out in the video, but function parameters are local variables as well and as such become part of closures:

The nice thing about closures is that you can create contexts for your functions as you go along. You can even use :

As John Resig says: It's all about closures. Superstructures like classes in other OOP languages are not needed to create context for methods. Which is not to say superstructures aren't needed at all. Visibility can become a problem in JavaScript. All methods of your code are exposed and can be called out of context and overwritten. That's why I would suggest to use the module pattern:

As you can see the message can be set from the outside, but it can only be output with displayMessage.

Personally I don't like stuffing everything into the return statement - which seems to be the classic version of the module pattern. That makes for very convoluted code. It's also difficult to find out at a glance what's public and what's not. I prefer "traditional" functions. By that I mean simply declaring them as I would in other languages instead of assigning them as values to propeties. That may be a matter of preference. Note however that the functions will not use their public versions when calling each other:

There's a bit more to the module pattern of course...