Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm writing a quite complex JavaScript application that has an MVC architecture that I'm implementing using Prototype's Class support and the Module pattern. The application uses AJAX and the Observer pattern. I create my controller instance when the DOM has loaded, pass it a view and some models created from JSON data and away it goes.

However, I've found that I have to set my controller instance as a property on the Window object—i.e. declare it without using var—because I have an AJAX success callback that refreshes the view object owned by the controller and at this point in the code my nice little MVC world is not in scope.

I investigated passing in the view object as a parameter to the function containing the AJAX code, but this got really messy and would have led to some horrible violations of the MVC pattern, such as coupling the model and the view. It was horrendous.

Is doing things like storing my controller instance directly on Window considered bad form? It smells a bit like using a global variable to me, but I can't see any way around it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
302 views
Welcome To Ask or Share your Answers For Others

1 Answer

Setting properties on the window object is equivalent to creating global variables. That is, sometimes doing it is inevitable, but you should try to keep it to a bare minimum, as it ends up polluting the global namespace.

In your case, creating a single property is not so bad. If you want to be extra careful about it, you can explicitly create a namespace for any stuff you need global access to:

// In init:
var mynamespace = {};

. . .

// Once the controller is available:
var namespace = window.mynamespace;
namespace.controller = controller;
namespace.foo = bar; // Set other stuff here as well.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...