DEV Community

Adam Crockett
Adam Crockett

Posted on • Updated on

Why decorators should be available everywhere

Please show your support!

Let's dive in, I believe this sample will explain better than words.

class SimpleRouter {
   @get '/home'
   ({ res }) {
      return res.html();

   @post 'submit/myform'
   ({ somePlugin, res }) {
Enter fullscreen mode Exit fullscreen mode

ps. what do you think about that slightly hacky syntax, cool huh?

But why can't this just be an object with decorators, I am forced to use a singleton for no good reason.

So people say you don't need classes but I'm afraid that syntactic sugar just keeps getting sweater.

Top comments (2)

seanmclem profile image

How is the code below a decorator connected to the decorator above it? Implicitly?

adam_cyclones profile image
Adam Crockett • Edited

Great question, yes decorators are implicitly connected to the next valid block of code they can find (JavaScript doesn't care about whitespace), that's why you can place a decorator above a method or inline.

@myDec someMethod(){}


@myDec(someInterceptingParam) someMethod(){}



Or in my case

@get ["/home"] // <- that's a method name

I could have done (probably should have done)

@get('/home') handleHomePage() {}

But you can see that this allows a URL to be used by two methods as the URL is now not tied to the method name and also there is more to type.