r3wt
r3wt

Reputation: 4742

Javascript Controller Loading/unloading

Most of these questions don't have very comprehensive answers.

say in my application, i've decided to call whatever controller is currently loaded something like $app.ctrl

now when i set $app.ctrl to null, what about any events that controller created?

for instance, my app might load a controller like this:

loadController : function(controller){
    $app.ctrl = null;
    var s = document.createElement('script');
    s.setAttribute('src', $app.ctrl_path+controller);
    s.className = 'ctrl';
    s.onload= function(){
        $app.ctrl = $ctrl;
        $app.ctrl.initialize();
    };
    document.body.appendChild( s );
},

How will events and instantiated plugins be cleaned up? what if my controller does lots of nasty stuff with jQuery plugins and adding event listeners and sech? Will GC really destroy these events, or will they secretly remain lurking, waiting to cause havoc: (suprise, they do)

var $ctrl = {

    initialize : function(){
        $(window).on('resize',function(){
            alert('you resized');
        });
    }

};

So what's the solution here? should my $app object define setters and getters for events, and a clean method for controllers? then the controller defiles a list targets and their events? so confused.

I think its pathetic that in 2015 javascript is this worthless in every modern browser.

Upvotes: 3

Views: 46

Answers (1)

krl
krl

Reputation: 5296

The solution is to have and call de-initialize function with .off():

reference:

https://api.jquery.com/off/

Upvotes: 2

Related Questions