6. Declarative and imperative targets
Targets in TargetJS can be defined in two ways: declarative or imperative.
The declarative approach offers a structured method for defining targets, as seen in the previous example.
However, orchestrating multiple targets can be still challenging.
For instance, tracking the completion of multiple targets to trigger a new set of targets is not easily done using only declarative targets.
To address this, TargetJS provides the setTarget
function,
allowing you to define multiple imperative targets from within a single declarative target.
Additionally, the onImperativeStep
and onImperativeEnd
callbacks, defined in the declarative target,
enable you to track each step of the imperative targets or just their completion.
By combining both declarative and imperative targets, you gain a powerful toolset for designing complex interactions.
The following example demonstrates the usage of both declarative and imperative targets.
Or in HTML:
<div
tg-colors="['aliceblue', 'burlywood', 'darkgoldenrod', 'darkorange', 'firebrick', 'lavender']"
tg-children="{
cycles: 9,
interval: 100,
value: function() {
return {
width: 50,
height: 50,
background: {
cycles: 1000,
steps: 50,
value: function() {
return this.getParentValue('colors')[Math.floor(Math.random() * 6)];
}
},
animate: {
value: function() {
var width = this.getWidth();
var parentWidth = TargetJS.getScreenWidth();
this.setTarget('x', { list: [ -width, parentWidth + width ] }, Math.floor(300 * Math.random()));
this.setTarget('y', Math.floor(Math.random() * (this.getParentValue('height') - this.getHeight())), 30);
},
onXEnd: function() {
this.activateTarget(this.key);
}
}
};
}
}"
tg-width="function() { return TargetJS.getScreenWidth(); }"
tg-height="function() { return TargetJS.getScreenHeight(); }"
/>
</div>
It can also be written as:
<div
tg-colors="['aliceblue', 'burlywood', 'darkgoldenrod', 'darkorange', 'firebrick', 'lavender']"
tg-width="function() { return TargetJS.getScreenWidth(); }"
tg-height="function() { return TargetJS.getScreenHeight(); }"
tg-children="{ cycles: 9, interval: 100 }"
>
<div
tg-width="50"
tg-height="50"
tg-background="{
cycles: 1000,
steps: 50,
value: function() {
return this.getParentValue('colors')[Math.floor(Math.random() * 6)];
}
}"
tg-animate="{
value: function() {
var width = this.getWidth();
var parentWidth = TargetJS.getScreenWidth();
this.setTarget('x', { list: [ -width, parentWidth + width ] }, Math.floor(300 * Math.random()));
this.setTarget('y', Math.floor(Math.random() * (this.getParentValue('height') - this.getHeight())), 30);
},
onXEnd: function() {
this.activateTarget(this.key);
}
}"
></div>
</div>