Search code examples
javascriptjqueryobject-literal

Undefined function in object literal scroll


Hi Im trying to make an image gallery similar to instagram that loads images on scroll. Im trying it as an object literal variable but am getting an undefined method for this.showPics... getMore is called from an ajax success method. Is this a scope issue because of the scroller being called in the .scroll? How should I do this? BTW showPics is defined I just didnt paste it in.. Thanks

var Pics{
    showPics: function() {
        //loop thru images
    }
    scroller: function() {
        if ($(window).scrollTop() + $(window).height() == $(document).height()) {
            this.showPics();
        }
    }
    getMore: function(){
        $(window).scroll(this.scroller);
    }
}

Solution

  • In the function, this doesnt refer to the object anymore, but to the window. Try using bind like that :

    $(window).scroll(this.scroller.bind(this));
    

    It will change the reference of this inside the scroller function to the current object.

    Also, you have syntax errors in your object, but I assume that you just made a pseudo code for the question, right?