Search code examples
ractivejs

Can Ractive events work in markup rendered with the triple-stash syntax?


If I have the following in my Ractive template:

<span on-click='handleClick'>click me</span>

Then I can listen for the click with this:

app.on({
    handleClick:function() {
        alert("clicked!") ;
    }
})

But lets say I have that same markup stored in a string variable called clicklyspan:

app.set("clicklyspan", "<span on-click='handleClick'>click me</span>")

and I render it in the template using the triple-stash syntax:

{{{clicklyspan}}} 

The handleClick listener no longer gets fired. Is there anything I can do to force some kind of update to the rendered template so that the listener works? Say, after I do that app.set() call?

Here's a fiddle demonstrating the problem.

Thanks, Dave


Solution

  • I have never used Ractive, but I did some research and it seems you have to use partials, like this:

    var app = new Ractive({
      el: 'container',
      template: '#template',
      data: {
        myFunction: function() {
            var template = '<a on-click="handleClick">I can now be clicked as well!</a>';
            if (!this.partials.myFunction) {
                this.partials.myFunction = template;
            }
            else {
                this.resetPartial('myFunction', template);
            }
            return 'myFunction';
        }
      }
    });
    

    You will also need to use this instead of the triple mustache:

    {{> myFunction() }}
    

    Here's the corresponding jsfiddle.

    Of course, replace myFunction with whatever name you like.

    Related question I found useful:

    RactiveJS events on tripple mustache