Search code examples
javascriptjqueryclassoopmootools

Mootools Class to Jquery


I'm converting a mootools class to Jquery, but I'm with a problem at the moment.

I've the following code (mootools)

var ListaItens = new Class({

    ...

    ...

    initialize: function(element){
        ....

        this.btnAdd = this.tabela.getElement('.add_linha button');
        if(this.btnAdd){
            this.btnAdd.addEvent('click', this.addLinha.bindWithEvent(this));
            this.checkAdd();
        }

        ...
    },

    addLinha: function(){

    }   
});

Now in Jquery I've this

var ListaItens = function(element, maxLinhas){

    ...

    this.btnAdd = this.tabela.find('.add_linha button')[0];
    if(this.btnAdd){
        //$(this.btnAdd).proxy('click', this.addLinha);
        $(this.btnAdd).on("click", this.addLinha);
        this.checkAdd;
    }

    ...

    this.addLinha = function(){

    }
})

My problem is how to bind the addline function to btnAdd. My code isn't work because the element 'this' change. And I don't know how to convert the function bindWithEvent to jquery.

Any solution?

Thanks in advance


Solution

  • As far as I know, jQuery does not provide a similar concept of classes as mootools does, so one thing you can do is to use the »classic JS approach« to create classes like so:

    function ListaItens () {
        var that = this;
    
        this.tabela = $(…);
        this.btnAdd = this.tabela.find(…);
    
        if (this.btnAdd) {
            this.this.btnAdd.on('click', function (e) {
                that.addLinha();
            })
        }
    }
    
    ListaItens.prototype.addLinha = function () {
    
    }
    
    var instance = new ListaItens();
    

    So, to answer your question: What you basically need to do is to keep a reference to the »original this«