Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript & Jquery: what is the best practice to call a class into Jquery onclick function?

I don't want instantiate a class in each function. How to? What should be the best practice to organize this in a Typescript syntax?

$(".container_dettaglio .varianti .variante a").click(function (event) {
    event.preventDefault();
    var pr = new Prodotto($(this).data('variante'));
    pr.cambiaVariante();
});

$(".meno").on('click',function(e){
    e.preventDefault();
    var pr = new Prodotto($(this).data('variante'));
    pr.rimuoviQuantita();
});

$(".piu").on('click',function(e){
    e.preventDefault();
    var pr = new Prodotto($(this).data('variante'));
    pr.aggiungiQuantita();
});
like image 568
marco Avatar asked Oct 31 '22 04:10

marco


1 Answers

The best workaround (I think) you can do is to restructure your class to return functions which will do your desires. This is an example of what I mean:

var MyClass = function(){
    return {
        Set: function(a, b, c){
            return [a, b, c].toString();
        },

        Modify: function(a){
            return a + ' .)';
        }
    }
};

$(function(){
    var mc = new MyClass();

    $('.a').on('click', function(){
        alert( mc.Modify($(this).data('variant')) );
    });

    $('.b').on('click', function(){
        alert( mc.Modify($(this).data('variant')) );
    });

});

So, by this way you instantiate your class once. Check the jsFiddle

like image 64
kosmos Avatar answered Nov 12 '22 19:11

kosmos