Differentiating between injected services vs variables in Controllers
pjlong opened this issue · comments
In migrating function-based Controllers to class-based Controllers, the injected services instead of being in the function's scope, has to be attached to the class instance to be used in the methods.
Example:
// function-ctrl.js
function functionCtrl (fooService) {
var vm = this;
vm.counter = 0;
vm.doFoo = doFoo;
function doFoo () {
vm.counter++;
return fooService.doThing();
}
}
// class-ctrl.js
class classCtrl {
constructor (fooService) {
this.fooService = fooService;
this.counter = 0;
}
doFoo () {
this.counter++;
return this.fooService.doThing();
}
}
I've toyed around with the idea of having a "service" object to sort of "namespace" the services inside of a class, and there's also the weakmap method
// class-ctrl.js
class classCtrl {
constructor (fooService) {
this.$ = {
fooService: fooService
};
this.counter = 0;
}
doFoo () {
this.counter++;
return this.$.fooService.doThing();
}
}
What's the best/preferred way? Is there a better way to separate out injected services vs vm variables and methods? Or is it OK to keep them with the class instance?
I find it easier to understand and maintain it simply in "this" context, while attaching the injected services to "this" context with "Object.assign".
OK, yeah that's mostly the way I've been leaning towards too. I suppose with proper naming, variable/method collisions shouldn't be that big of a concern.
great.