3

Inside the initialize() function there is a jQuery each loop. Inside that loop is a reference to this.dbcolumns which is obviously not working as jQuery has reassigned this to the current loop element. So how can I reference this.dbcolumns from inside the loop? It works outside the loop ok.

function datatable() {
    this.url = '';
    this.htmltable = '';
    this.dbtable = '';
    this.dbcolumns = new Array();
    this.idfield = 'id';
    this.pageno = 0;
    this.pagesize = 15;
    this.totalpages = 0;
    this.totalrecords = 0;
    this.searchterm = '';

    this.initialize = function() {
        this.dbtable = $(this.htmltable).attr('data-table');
        this.dbcolumns.push(this.idfield);
        $(this.htmltable + ' th[data-field]').each(function(i, col){
            this.dbcolumns.push( $(col).attr('data-field') ); /* <<<<<<<<<< this line */
        });
        return this;
    }
} 
2
  • 1
    var that =this then use that... Commented Jun 17, 2012 at 10:01
  • 1
    Side note: function expressions should have a trailing semicolon. Commented Jun 17, 2012 at 10:03

3 Answers 3

14

make a reference to the "this" that you want to hold onto outside of the loop.

var self = this;

then you can use "self" inside the loop.

Sign up to request clarification or add additional context in comments.

Comments

4

Store a reference to this outside the each callback, or use the ES5 bind method:

$(this.htmltable + ' th[data-field]').each(function(i, col){
     this.dbcolumns.push( $(col).attr('data-field') );
}.bind(this));

Or, as noted in the comments use $.proxy:

$(this.htmltable + ' th[data-field]').each($.proxy(function(i, col){
     this.dbcolumns.push( $(col).attr('data-field') );
}, this));

2 Comments

With jQuery it may be advisable to use $.proxy because .bind is not supported everywhere.
True. I've been working a lot with PrototypeJS recently (which shims bind for you), so I keep mixing up jQuery patterns and Prototype patterns.
3

The common JS pattern to solve is to use closure:

this.initialize = function() {
    var that = this;

    this.dbtable = $(this.htmltable).attr('data-table');
    this.dbcolumns.push(this.idfield);
    $(this.htmltable + ' th[data-field]').each(function(i, col){
        that.dbcolumns.push( $(col).attr('data-field') ); /* <<<<<<<<<< this line */
    });
    return this;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.