DEV Community

Michael Bogan for Salesforce Developers

Posted on

Decorators and Mixins in Lightning Web Components

Decorators and Mixins in Lightning Web Components

It's safe to say that every modern web application these days relies to some degree on three foundational web standards: HTML, CSS, and JavaScript. While HTML has largely stabilized since the HTML5 standard, both CSS and JavaScript continue to evolve to meet developers' and users' needs.

The evolving nature of these three technologies has lead to the introduction of web components, a cross-browser solution for building complex web apps. On top of this open source standard, Salesforce developed Lightning Web Components (LWC) as a fast, enterprise-grade wrapper around vanilla web components. The result is a thin, performant, and feature-packed framework built entirely on the open web.

LWC is not only built on top of the ECMAScript standard, it also provides some nifty syntactic sugar that can transpile into standard JavaScript. Because of this, the LWC framework is able to incorporate proposed language features, which simplifies app development by future proofing your code in the always evolving JavaScript ecosystem. In this post, we'll take a closer look at two relatively recent features—mixins and decorators—and see how they can be used in your LWC apps.

What is a Mixin?

In many object-oriented programming languages, classes can "receive" additional methods through a feature called inheritance. For example, if you have a Vehicle class with the methods go and stop, subclasses like Bicycle and Car can implement them directly:

class Vehicle {

  void go();

  void stop();

}

class Bicycle < Vehicle {

  void go() {

    usePedal();

  }

  void stop() {

    stopPedal();

  }

}

class Car < Vehicle {

  void go() {

    useEngine();

  }

  void stop() {

    stopEngine();

  }

}
Enter fullscreen mode Exit fullscreen mode

Inheritance affects the composition of an object by changing its hierarchy. Every Bicycle and Car is now also a Vehicle. But what if you merely wanted to add in common methods to objects without dealing with any parent class? That's what a mixin does.

In a JavaScript context, mixins can add behaviors to JavaScript classes, which is useful, because classes can only extend from one other class, while multiple mixins can be added to a class. Mixins take advantage of the Object.assign method, which copies all of the properties from one object onto another:

// mixin

let greetingsMixin = {

  sayHi() {

    alert(`Hello ${this.name}`);

  },

  sayBye() {

    alert(`Bye ${this.name}`);

  }

};

class User {

  constructor(name) {

    this.name = name;

  }

}

// copy the methods

Object.assign(User.prototype, greetingsMixin);
Enter fullscreen mode Exit fullscreen mode

User can now call sayHi and sayBye natively. Per JavaScript rules, User can also inherit from just one class, while including properties and function) from any number of mixins:

class User extends Person {

  // ...

}

Object.assign(User.prototype, greetingsMixin);

Object.assign(User.prototype, someOtherMixin);
Enter fullscreen mode Exit fullscreen mode

However, writing out Object.assign is somewhat akin to littering your code. What's worse is figuring out what the method is doing isn't very intuitive. Through some native JavaScript syntax, you can actually create a "subclass factory" with mixins, and declare which mixins you're using right at the top:

class User extends greetingsMixin(Person) {

  // ...

}
Enter fullscreen mode Exit fullscreen mode

(For more information on this technique, check out this article.)

Now, User includes the greetingsMixin and inherits from the Person class, all in one line.

This technique is more than syntactical sugar: it's actually the one which LWC regularly prefers. For example, the Navigation Mixin provides methods that are useful to navigational UI elements, but ultimately, each class that includes it should also derive from a plain LightningElement:

import { LightningElement } from 'lwc';

import { NavigationMixin } from 'lightning/navigation';

export default class TestComponent extends NavigationMixin(LightningElement) {

  // ...

}
Enter fullscreen mode Exit fullscreen mode

NavigationMixin provides functionality that's crucial to components dealing with navigating through pages, while LightningElement provides all the base functionality for every component. Thus, TestComponent will need to include NavigationMixin and subclass from LightningElement, and can do so in the easy-to-see, single-line format.

What is a Decorator?

Decorators are currently a proposal to add to JavaScript, but they're so incredibly useful that many frameworks already support them. In essence, a decorator is a function that can modify a class, or any of its properties and methods. That's a pretty high-level definition, so let's take a look at what that means in practice.

Suppose we have a class like this:

class User {

  constructor(firstName, lastName) {

    this.firstName = firstName;

    this.lastName = lastName;

  }

  getFullName() {

    return `${this.firstName} ${this.lastName}`;

  }

}
Enter fullscreen mode Exit fullscreen mode

Now, any code which makes use of this class can create a user:

let user = new User("Jane", "Eyre");

user.getFullName(); // returns "Jane Eyre"
Enter fullscreen mode Exit fullscreen mode

But because of the way JavaScript is designed, a developer could inadvertently change the getFullName method if they so desired:

let user = new User("Jane", "Eyre");

user.prototype.getFullName = function() {

  return "not the name!;"

}

user.getFullName(); // returns "not the name!"
Enter fullscreen mode Exit fullscreen mode

Now, this is obviously a trite example, but the danger still remains. You can write code to make a class property read-only, like this:

Object.defineProperty(User.prototype, 'gettFullName', {

  writable: false

});
Enter fullscreen mode Exit fullscreen mode

This works, but it's obviously cumbersome to write for multiple properties.

Enter decorators. You can define a decorator function to apply any behavior you want to a target property. For example, to set a target as writable: false, you could do this:

function readonly(target) {

  target.descriptor.writable = false;

  return target;

}
Enter fullscreen mode Exit fullscreen mode

We just defined a decorator called readonly which, when passed a target, sets its descriptor.writable property to false. This can be applied to our User class like this:

class User {

  // ...

  @readonly

  getFullName() {

    return `${this.firstName} ${this.lastName}`;

  }

}
Enter fullscreen mode Exit fullscreen mode

Voila! The same functionality, in a single line of code.

LWC provides several decorators for developers to use. They are:

  • @api: by default, every property is hidden and private. @api exposes it publicly.
  • @track: this marks a property as reactive, which means that when its value changes, the web component will re-render and display the new value.
  • @wire: this is a decorator which signifies that we want to read Salesforce data.

These three decorators, which are unique to LWC, aim to help reduce rewriting the same code while easily providing common functionality.

Conclusion

Since LWC is built on web standards, it can leverage native APIs and languages in order to make developers immediately productive, since they're using existing skills rather than learning proprietary techniques.

If you'd like to take a closer look at Lightning Web Components, Salesforce has a boilerplate app that's built in TypeScript. There's also a Trailhead lesson to help you learn about web components in less than an hour. Or, feel free to check out the LWC dev docs for more specific reference information.

Top comments (0)