Referring To Child Properties In Ractive.js
New to Ractive.js and after reading over the docs I'm still hung up on some of the syntax. My example below creates a canvas tag for each element in my array and then instantiates
Solution 1:
I think what you're missing is adding the array of CanvasSprite objects to the Ractive data, and then using the event context to get the current sprite (see https://jsfiddle.net/martypdx/srbvekc4/2/ for full example):
var CanvasAnimation = Ractive.extend( {
template: `
{{#each sprites}}
<li on-click='setFrame'>{{.id}}</li>
{{/each}}`,
oninit() {
var sprites = this.get('repeaters').map( function(repeater){
returnnew CanvasSprite(repeater.id, repeater.width, repeater.height, repeater.spriteSheetURL, repeater.rows, repeater.columns, repeater.totalFrames);
});
// add the class instances to the datathis.set( 'sprites', sprites );
this.on('setFrame', function (event) {
// here's how we get the sprite from the eventvar sprite = event.context;
var offsetY = event.original.clientY - event.node.getBoundingClientRect().top;
var relY = offsetY/sprite.height;
sprite.setFrame(relY);
});
},
onrender() {
// wait till render, otherwise nothing there!this.get( 'sprites' ).forEach( sprite => sprite.setFrame(0) );
}
});
EDIT: You can also use components to better encapsulate each sprite (see https://jsfiddle.net/martypdx/srbvekc4/1/):
var CanvasAnimation = Ractive.extend( {
template: `
{{#each repeater}}
<Sprite options='{{this}}'></Sprite>
{{/each}}`
});
var Sprite = Ractive.extend({
template: `<li on-click='setFrame'>{{sprite.id}}</li>`,
oninit() {
const sprite = new CanvasSprite( repeater.id, repeater.width, repeater.height, repeater.spriteSheetURL, repeater.rows, repeater.columns, repeater.totalFrames );
// since example template is using properties from sprite,// we add it to the datathis.set( 'sprite', sprite );
this.on('setFrame', function (event) {
var offsetY = event.original.clientY - event.node.getBoundingClientRect().top;
var relY = offsetY/sprite.height;
sprite.setFrame(relY);
});
},
onrender() {
this.sprite.setFrame(0);
}
});
var canvasAnimation = new CanvasAnimation({
el: document.body,
template: '#template',
data: { repeaters: repeater },
components: { Sprite }
});
UPDATED: Use multi-parameter constructor and also realized better encapsulation if component handles instantiation of CanvasSprite
.
Post a Comment for "Referring To Child Properties In Ractive.js"