beingalex
beingalex

Reputation: 2476

How to use "this" in Javascript

I have this piece of code:

this.json.each(function(obj, index) {
    var li = new Element('li');
    var a = new Element('a', {
        'href': '#',
        'rel': obj.id,
        events: {
            'click': function(e) {

                this.doSteps(this.step + 1); // <-- causing issue

            }
        }   
    });
    var img = new Element('img', {
        'src': imgd + obj.img,
        'alt': obj.name                        
    });
    img.inject(a);
    a.inject(li);
    li.inject(ul);
});

I get an error of "this.doSteps is not a function" in the console. Can somebody please help me with this and explain the resolution.

Thanks in advance.

Upvotes: 2

Views: 1123

Answers (5)

loddn
loddn

Reputation: 658

You can pass this in a each function with ,this.

this.json.each(function(obj, index) {


    }, this);

Upvotes: 0

Oskar Krawczyk
Oskar Krawczyk

Reputation: 3502

You need to bind this, so the scope of the function is referring to the right this.

'click': function(e) {
    this.doSteps(this.step + 1);
}.bind(this)

This is the MooTools way.

Upvotes: 3

Adam Zalcman
Adam Zalcman

Reputation: 27233

On the line causing the issue this refers to the object the function belongs to, i.e. to events, which indeed doesn't have any member named doSteps.

Upvotes: 0

Qchmqs
Qchmqs

Reputation: 1805

try to use e the element you're currently working on

this.json.each(function(obj, index) {
    var li = new Element('li');
    var a = new Element('a', {
        'href': '#',
        'rel': obj.id,
        events: {
            'click': function(e) {

                e.doSteps(e.step + 1); // <-- here the e from the function is your element

            }
        }   
    });
    var img = new Element('img', {
        'src': imgd + obj.img,
        'alt': obj.name                        
    });
    img.inject(a);
    a.inject(li);
    li.inject(ul);
});

Upvotes: -1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

Try capturing it in a closure:

var li = new Element('li');
var _self = this;
var a = new Element('a', {
    'href': '#',
    'rel': obj.id,
    events: {
        'click': function(e) {

            _self.doSteps(_self.step + 1); // <-- causing issue

        }
    }   
});

Upvotes: 1

Related Questions