I recently started trying out Ractive.js. I was particularly interested in its components. One of the things I noticed immediately is that many of the examples are using the init
option. However when I try to use the init
in my code I get a deprecation notice and it then recommends using onrender
instead. onrender
however had far fewer examples than init
and some of the functions such as this.find
weren't available inside onrender
. I looked through the Github issues but couldn't find any reasoning behind this change or what the suggested path forward for selecting elements specific to a component was.
I created a test pen to try creating a recursive component with the new API but I had to resort to using jQuery and an undocumented fragment
api to select specific DOM nodes I needed to manipulate. I feel this is against how Ractive expects you to do things, but I couldn't figure out what was expected of me with the existing documentation.
What's the major differences between the init
and onrender
options and how does onrender
expect you to handle manipulating specific elements and their events within a component?
You can use this.find()
inside onrender
(if you can't for some reason, you've found a bug!).
We split init
into oninit
and onrender
a while back for a number of reasons. Those examples you mention are out of date - are they somewhere on ractivejs.org? If so we should fix them. You can find more information about lifecycle events here on the docs, but the basic difference is this:
init
was called on initial render (assuming the component was rendered, i.e. never in node.js, if you were doing server-side rendering)oninit
is called on creation, immediately before rendering. It is called once and only once for any Ractive instance, whether or not it gets rendered. It's therefore a good place to set up event handlers etc. The opposite of oninit
is onteardown
, so you can use that handler to do any cleanup if necessary (or use this.on('teardown'...)
inside oninit
).onrender
is called whenever a component is rendered. This could happen more than once (if you unrendered, then re-rendered, etc) or not at all. If you need to store DOM references etc, this is the place. The opposite of onrender
is onunrender
.I did a fork of your codepen, replacing the jQuery stuff with more idiomatic Ractive code to show how you'd do it without storing DOM references.