Skip to content

Migration guide (from v2 to v3)

Mingyu Kim edited this page Mar 4, 2021 · 1 revision

Component's v3 is designed to improve the following shortcomings of the existing v2.

1. Fixed default property and forcing the object type to the first event property

Traditional we had to use properties like 'eventType' or 'stop()' even if they aren't necessary. In v3, we've created a new class called ComponentEvent, which allowed us to include these basic properties only when they're needed.

import Component, { ComponentEvent } from "@egjs/component";

// Now it's available to use non-object types such as number and string.
class Derived extends Component<{
  event1: number;
  event2: string;
  event3: void;
  event4: ComponentEvent<{ additionalProp: number }>;
  event5: ComponentEvent; // When there're no additional properties
  event6: (a: number, b: string) => void;
}> {
  // ...
}

2. Unable to use interface when specifying event type

When using the type inference feature, the interface could not be designated as the event types triggered by the component due to problems in adding the above basic properties to the type. In v3, it is now available to use interface as event types definition.

import Component from "@egjs/component";

interface DerivedEvents {
  event1: string;
  event2: number;
}

class Derived extends Component<DerivedEvents> {}

Code migration guide

You can use 'ComponentEvent' to simply migrate the same as the previous code.

v2

import Component from "@egjs/component";

class Derived extends Component<{
  event1: { prop1: number; prop2: string };
  event2: void;
}> {
  // ...
}

const component = new Derived();
// Triggering events
component.trigger("event1", { prop1: 123, prop2: "abc" });
component.trigger("event2");

v3

import Component, { ComponentEvent } from "@egjs/component";

class Derived extends Component<{
  event1: ComponentEvent<{ prop1: number; prop2: string }>;
  event2: ComponentEvent;
}> {
  // ...
}

const component = new Derived();
// Triggering events
component.trigger(new ComponentEvent("event1", { prop1: 123, prop2: "abc" }));
component.trigger(new ComponentEvent("event2"));

In addition, by adding the 'isCanceled()' method to 'ComponentEvent', the 'trigger' method, which had previously returned whether 'stop()' of the event was called, was changed to return 'this'. The resulting code changes are as follows:

v2

const component = new Component();

if (component.trigger("event")) {
  // ...Codes for when stop() is not called...
}

v3

const component = new Component();
const event = new ComponentEvent("event");
component.trigger(event);

if (!event.isCanceled()) {
  // ...Codes for when stop() is not called...
}