Unwanted multiple instances of the same function

By : qua1ity
Source: Stackoverflow.com
Question!

I have this in my controller:

var page = 2;

$($window).scroll(function () {
    if($($window).scrollTop() == $(document).height() - $($window).height()) {
        myService.addMore(page);
        page++;
        console.log("page: " + page);
    }
});

This function runs when you scroll to the bottom of the page. The function then calls myService with the page value as a parameter. The service function is just a http request like this:

factory.addMore = function (page) {
    $http({
        method: "GET",
        url: "url..." + page,
    }).success....
}

Every time you scroll down, the service makes a http request with the page value and some data gets printed to the view. While the page variable adds 1 every time, which it should.

However, there is a problem if you trigger the function by scrolling down, and then navigate to another page on the site, and then back again to the page with the scroll function.

The console.log outputs this:

  • You scroll down, output: page: 3
  • Scroll down more, output: page 4
  • Change page, then back to scroll page and scroll down again, output: page 5 and page: 3

So now suddenly it seems like i have two of these functions running, which is a problem. How can i fix this? The page value should reset to 2 every time you go back.

I'm using ui router to change between states.

Let me know if you need any more information.

By : qua1ity


Answers

You are binding the listener to the window object. Which persists through states in a single page application. Either unbind the listener at state redirect or bind it to an element that gets deconstucted at state redirect (i.e. something in the template of the state).



This video can help you solving your question :)
By: admin