JQuery.click () with unanonymus method problem

I follow and modify the tutorial in the hope of creating an interactive skills sheet.

var main = function() {
    var points = parseInt($('.resume').text());
    var pointExpended = 0; 


    $('.node').click(function() {
        var cost = parseInt($(this).children('.info').children('.cost').text());
        if($(this).hasClass('active-node')) {
            //l'abilità viene rimossa 
            $(this).removeClass('active-node');
            pointExpended = pointExpended - cost;
            $('.resume').text(points-pointExpended);
        }
        else {
            //l'abilità viene comprata
            if(points-(pointExpended+cost) < 0) {
                alert("Limite dei punti superato");
            }
            else {
            $(this).addClass('active-node');
            pointExpended = pointExpended + cost;
            $('.resume').text(points-pointExpended);
            }
        }
    });
   };


   $(document).ready(main);

to add some recursion, I'm trying to put a handler in an external function

var click_handler = function() {

        alert(points);

        var cost = parseInt($(this).children('.info').children('.cost').text());
        if($(this).hasClass('active-node')) {
            //l'abilità viene rimossa 
            $(this).removeClass('active-node');
            pointExpended = pointExpended - cost;
            $('.resume').text(points-pointExpended);
        }
        else {
            //l'abilità viene comprata
            if(points-(pointExpended+cost) < 0) {
                alert("Limite dei punti superato");
            }
            else {
            $(this).addClass('active-node');
            pointExpended = pointExpended + cost;
            $('.resume').text(points-pointExpended);
            }
        }
    }

var main = function() {
    var points = parseInt($('.resume').text());
    var pointExpended = 0; 

    alert(points);

    $('.node').click(click_handler);
};


$(document).ready(main); 

but the code does not respond to clicks.

I am new to jscript / jquery, so I can not understand why the first attempt works, and not the last

+4
source share
1 answer

variable pointsand are pointEtendednot visible to your click handler (the scope variable is lexical material and does not work in the call stack), so you need to pass them with the closure:

var main = function() {
    var points = parseInt($('.resume').text());
    var pointExpended = 0; 

    alert(points);

    $('.node').click(function(evt) {
              click_handler(evt, points, pointExtended)
    });
};

also change click_handler to accept named values

click_handler(evt, points, pointExtend) { ...
}
+2
source

Source: https://habr.com/ru/post/1621890/


All Articles