2. Overview
Targets provide a unified interface for both variables and methods. Each Target comes equipped with a built-in set of capabilities:
1. Iterations: They can iterate towards defined values, making them perfect for creating animations.
2. Multiple or Conditional Execution: Targets can execute repeatedly or only under specific conditions.
3. Execution timing: Targets enable fine-grained control over when they execute.
4. State Management: Targets are inherently stateful, enabling implicit state handling across your application.
5. Code-Ordered Execution: Targets execute sequentially and predictably in the order they are written within a JavaScript object, thanks to ES2015's guaranteed property order.
Let’s look at a simple example of a box that animates its height and width to demonstrate how targets work.
First, some targets may look like regular properties or methods, but they are internally wrapped and managed by TargetJS.
Second, targets execute in the exact order they are defined in the code.
In this example, the targets run in sequence: background
, then width
, and finally height$
:
1. background
: This target runs first, setting the element's background color to mediumpurple. Once the assignment is complete,
its lifecycle ends.
2. width
: Next, the width target takes over. It's configured to animate through a list of values (100, 250, 100),
performing 50 steps with a 10ms pause between each step, creating a grow-then-shrink effect.
3. height$
: Finally, the height$ target demonstrates TargetJS's reactivity. Because its name ends with a single $
postfix,
height$
is explicitly declared to react whenever its immediately preceding target (width) executes on every step.
As width animates and changes its value, height$
automatically re-runs, setting its value to half of width
's value.
Or in HTML:
<div
tg-background="mediumpurple"
tg-width="[{ list: [100, 250, 100] }, 50, 10]"
tg-height$="return this.prevTargetValue / 2"
>
</div>