事件处理函数不适用于“this”关键字

Event handling function not working with `this` keyword

本文关键字:this 关键字 适用于 处理函数 不适用 事件      更新时间:2023-09-26

为什么我不能从事件处理程序中的this关键字获取数据,如何修复?

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;
});

做这个改变

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;
});

首先,您需要创建一个类的对象UnShown然后您可以访问其属性。

编辑 2 :如果你想随时创建对象,你可以通过这种方式来完成。

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()

通过在Unshown函数中使用 this 关键字,可以设置该函数对象的属性。若要访问函数外部的这些属性,请在函数对象引用上使用属性访问器。

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;
});

在 AngularJS 中使用window.onscroll

使用 window.onscroll 是注册事件侦听器的旧方法。

在 AngularJS 中,事件侦听器是使用 Angular 的 jqLite 添加的。

var windowElem = angular.element($window);
windowElem.on('scroll', function scrollListener (event) {
    console.log(event);
};

请务必将$window添加到工厂功能的注射剂列表中。