Click/Reset Button

Asked

Viewed 79 times

0

I have the following code:

HTML:

<div class='liveExample'> 

    <div><span data-bind='text: numberOfClicks'>&nbsp;</span></div>

      <div data-bind='visible: hasClickedTooManyTimes'>
        <button data-bind='click: resetClicks'>Reset clicks</button>
    </div>

    <button data-bind='click: registerClick, disable: hasClickedTooManyTimes'>Click me</button>


</div>

Javascript:

var ClickCounterViewModel = function() {
    this.numberOfClicks = ko.observable(0);

    this.registerClick = function() {
        this.numberOfClicks(this.numberOfClicks() + 1);
    };

    this.resetClicks = function() {
        this.numberOfClicks(0);
    };

    this.hasClickedTooManyTimes = ko.computed(function() {
        return this.numberOfClicks() >= 99;
    }, this);
};

ko.applyBindings(new ClickCounterViewModel());

That makes me have a button (Click Me) where whenever I click, the number changes upwards (from 1 to 99). Every time it gets to 99, I see another button (Reset Me) that brings the count back to the beginning. - this makes it necessary to have two buttons.

What I would like to understand is: is it possible to put everything in one button? I believe it is a Javascript function that I do not know.

  • Welcome Claukms, avoid putting screenshots of the code. Edit your question and put your code!

  • Thanks Luiz, I’ve changed. You can help me?

1 answer

1


If what you want is that the same button that increments, when arriving at 99° click itself reset and back from the beginning, could do the following, in the registerClick function puts it to check if it reached the maximum value, if hit reset.
Would that be the code:

HTML

<div class='liveExample'> 
<button data-bind='click: registerClick'>Click me</button>  
</div>

Javascript

var ClickCounterViewModel = function() {
    this.numberOfClicks = ko.observable(0);

    this.registerClick = function() {
        if(this.numberOfClicks() >= 99){
            alert('Atingiu o limite, vamos resetar');
            this.resetClicks();
        }else{
            this.numberOfClicks(this.numberOfClicks() + 1);
        }
    };

    this.resetClicks = function() {
        this.numberOfClicks(0);
    };

    this.hasClickedTooManyTimes = ko.computed(function() {
        return this.numberOfClicks() >= 99;
    }, this);
};

ko.applyBindings(new ClickCounterViewModel());
  • Thank you so Much! It worked!

  • I’m Glad i can help you! If this Answer helps you, Please consider mark it as correct one.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.