1

Why can't I get data from this keyword in event handler and how can it be fixed?

twittyApp.factory('Unshown', function () {
function Unshown() {
    this.allIsLoaded = false;
    this.loading = false;
    this.firstTime = true;
    this.scrollMarker = 100;
    this.loadedUnshownPages = 0;
    this.timeLineHiader = $cookies.get("lastReadedTweetId");
}
window.onscroll = function () {
     //why here this.scrollMarker is undefined?
};
return Unshown;
});
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Andrew
  • 15
  • 6

2 Answers2

1

Do this changes

twittyApp.factory('Unshown', function() {

    var fact = {};

    function Unshown() {
        this.allIsLoaded = false;
        this.loading = false;
        this.firstTime = true;
        this.scrollMarker = 100;
        this.loadedUnshownPages = 0;
        this.timeLineHiader = $cookies.get("lastReadedTweetId");
    }

    var objUnShown = new Unshown();
    window.onscroll = function() {
        objUnShown.scrollMarker // aceess scrollmarker
    };

fact.Unshown =objUnShown;


    return fact.Unshown;
});

First you need to create an object of UnShown class then you can access their property.

EDIT 2 : if you want to create object whenever you want, you can do it in this way.

twittyApp.factory('Unshown', function() {

        var fact = {};

        function Unshown() {
             ..
        }

        window.onscroll = function() {
            objUnShown.scrollMarker // aceess scrollmarker
        };

    fact.Unshown =Unshown;


        return fact;
    });

 /// in controller do this.

 var objUnshown = new Unshown.Unshown()
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
0

By using the this keyword inside the Unshown functions, you are setting properties of that function object. To access those properties outside the function, use the property accessor on the function object reference.

twittyApp.factory('Unshown', function () {
function Unshown() {
    this.allIsLoaded = false;
    this.loading = false;
    this.firstTime = true;
    this.scrollMarker = 100;
    this.loadedUnshownPages = 0;
    this.timeLineHiader = $cookies.get("lastReadedTweetId");
}
window.onscroll = function () {
     //this.scrollMarker is undefined
     //
     //Use property accessor
     console.log(Unshown.scrollMarker);
};
return Unshown;
});

Using window.onscroll in AngularJS

Using window.onscroll is the Older way to register event listeners.

In AngularJS, event listeners are added using Angular's jqLite.

var windowElem = angular.element($window);

windowElem.on('scroll', function scrollListener (event) {
    console.log(event);
};

Be sure to add $window to the list of injectables for the factory function.

georgeawg
  • 48,608
  • 13
  • 72
  • 95