Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 759
r3wt Avatar asked Mar 11 '26 12:03

r3wt


1 Answers

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

reference:

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

like image 109
krl Avatar answered Mar 13 '26 02:03

krl