I have a normal client-side app written mostly in jQuery. I'm using Ractive on one specific page, where it's extremely useful. However, all of the old jQuery events are no longer attached, presumably because the DOM has been re-rendered after Ractive has been inited. I tried setting up the events after Ractive has rendered, but that resulted in some weird behavior, lost DOM elements and stuff. Where can I setup those old jQuery handlers, or is it possible? Is the Ractive rendering happening asynchronously, and if so, is there an event I should be listening to?
I've tried
$('.button').click(someHandler); // <--- Here
getData(function(data){
ractive = new Ractive({
el: '.content',
template: template,
data: data
});
});
and
getData(function(data){
ractive = new Ractive({
el: '.content',
template: template,
data: data
});
$('.button').click(someHandler); // <--- Also here
});
Beyond Rich's suggestion to use Ractive's event handling (which is most in-line with Ractive's way of doing thing) you can also use the complete option:
ractive = new Ractive({
el: '.content',
template: template,
data: data,
complete: function(){
$('.button').click(...)
// or better, use ractive's selector
// to limit search to the template.
// You could use this outside of `complete`
// as well.
$( this.find('.button') ).click(...)
}
});
Rather than fish around for the element, you can declaratively use a decorator to know when the element is created (and destroyed), and be handed a reference to it.. In your template:
<button decorator='initbutton'/>
Then in code:
ractive = new Ractive({
el: '.content',
template: template,
data: data,
decorators: {
initbutton: function(node){
var $button = $(node)
$button.on('click', ...)
return { teardown: function(){
//if you need to do anything to teardown...
$button.off('click', ...)
}
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With