angular / router

The Angular 1 Component Router
MIT License
665 stars 135 forks source link

static life-cylce hooks #215

Open SanderElias opened 9 years ago

SanderElias commented 9 years ago

When I add an life-cycle hook, I need to add it to the prototype in stead of using a static property. Now we need to do WelcomeController.prototype.canActivate = function () {} in stead of WelcomeController.canActivate = function () {}. The second source sample feels more natural to me. As controllers in this case will most often be a single instance in the app, there is in my opinion no added value by adding it to the prototype.

dcunited08 commented 9 years ago

@SanderElias I think partially the reason for that is ES6 classes.


class asdf{
    constructor(){

    }

    canActivate(){
        return true;
    }
}

Is the same as:


function asdf(){

};

asdf.prototype.canActivate = function(){
    return true;
}

You can do static functions but the general idea is the class will hold the state of the controller and the state isn't static.

SanderElias commented 9 years ago

@dcunited08 Sure, I do understand where it is coming from (indeed the way ES6 classes are build by default). There is one problem with prototype classes. You have to instantiate the class before you can access the life-cycle hooks. If you put them in static properties, they will be available before that. For example, take the canActivate hook. This one can prevent the controller from being instantiated right? See the problem? And later on, when the router becomes part of NG2.x it might be, that the router need to be statically analyzed for other stuff then DOM in the browser (virtual DOM, offline ussage, those are still wide open!) Static properties will be easier there too!

martinmcwhorter commented 9 years ago

I wonder if having a static resolve(), like ngRouter and uiRouter, separate from instance lifecycle hooks would solve this problem?

SanderElias commented 9 years ago

@martinmcwhorter Yes it would. However, the lifecycle hooks provide a way nicer API, and you can keep your 'resolve' alongside your controller. That is the place it belongs. one can use the canActivate hooks for things like (user) permissions and stuff like this. and the activate hook to fetch auxiliary data ($http stuff).

A static resolve pulls all of that away from the controller, and into a remotely connect part of your app. I don't think that's a good idea.