javascriptractivejs

change the on-click of a ractive button after each click


I have a ractive button that needs to change the functions after each click.

const template1 = '<button type="button" id="advanceButton" on-click="@this.advance()">Step1</button>'

ractive = new Ractive({
  el: '#container',
  template: template1,
  advance: function() {
    $("#advanceButton").html("Step2");
    
    //this.on-click change to advance2() //that that would be the desired behaviour
  }
});
ractive.on({
  advance2: function() {
    $("#advanceButton").html("Step3");
    //this.on-click change to advance3() //and so on...
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ractive/1.3.12/ractive.js"></script>
<div id="container"></div>

I tried to do it outside of ractive with $("#advanceButton").attr('onclick', 'advance2()') but despite the fact that it did not work either, I'd rather like to solve that inside ractive.


Solution

  • You could keep a value of current step and based on that call required function.

    const template1 = '<button type="button" id="advanceButton" on-click="@this.advance()">Step1</button>'
    
    ractive = new Ractive({
      el: '#container',
      data: { step: 1 },
      template: template1,
      advance: function() {
        var c_step = this.get("step") + 1;
        if( c_step === 4 )
            c_step = 1;
        this.set( "step", c_step );
        
        console.log( "Current step: " + c_step );
        
        if( c_step === 1 )
            this.step1();
        else if( c_step === 2 )
            this.step2();
        else if( c_step === 3 )
            this.step3();
      },
      
      step1: function() {
        $("#advanceButton").html("Step1");
      },
      
      step2: function() {
        $("#advanceButton").html("Step2");
      },
      
      step3: function() {
        $("#advanceButton").html("Step3");
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ractive/1.3.12/ractive.js"></script>
    <div id="container"></div>

    Hope this helps.