Kishore Patra
Kishore Patra

Reputation: 11

jQuery each function throwing error: Uncaught TypeError: Cannot read property

I'm creating a custom step.js application for my project. I'm getting error on object scope. Below is my code

var STEPPED = {
    el: {
        stepContentDiv: $('#stepContent'),
        stepNavDiv:     $('#stepNav'),
        stepNavLi:      $('#stepNav li'),
        stepNavAnchor:  $('#stepNav li a'),
        stepNavDone:  $('#stepNav li a'),
        stepNavActive:  $('#stepNav li a')
    },
    doActive: function(){
        this.el.stepNavDone.on('click', function(){
            this.el.stepNavLi.each(function(){
                alert();
            });
        });
    },
    init: function(){
        this.doActive();
    }
}
STEPPED.init();

Getting error when I run this

this.el.stepNavLi.each(function(){
    alert();
});

Uncaught TypeError: Cannot read property 'stepNavLi' of undefined

Can anyone pleas help me what is the issue here? Thanks in advance

Upvotes: 0

Views: 464

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337714

Within the click event handler function, this refers to the element that was clicked on, not the STEPPED object. You need to cache the reference to the object in a variable if you want to retain the reference to it within the click handler. Try this:

doActive: function() {
    var _stepped = this;
    _stepped.el.stepNavDone.on('click', function(){
        _stepped.el.stepNavLi.each(function(){
            alert();
        });
    });
},

Upvotes: 1

Related Questions