【问题标题】:Event handling function not working with `this` keyword [duplicate]事件处理功能不适用于`this`关键字[重复]
【发布时间】:2016-06-20 04:23:27
【问题描述】:

为什么我无法从事件处理程序中的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;
});

【问题讨论】:

  • 把window.onscroll放到Unshown函数里面
  • 如何在 onscroll 中访问 this.scrollMarker?
  • 'var scrolled ....... if (this.scrollMarker > scrolled && !this.loading && !this.allIsLoaded) { this.loading = true;}'

标签: javascript angularjs web frontend


【解决方案1】:

做这个改变

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”变量。就这些
  • 请粘贴错误
  • @riyaj-khan 您的解决方案有效,此评论用于解决此问题,但我在其他控制器中的非构造函数中得到了另一个意外结果 Unshown(),但这不是问题。谢谢你,祝你好运!
  • 哦,现在这个处理程序在每个页面上都可以使用,它不是很好,它在登录页面中崩溃,然后在主页上不起作用。
  • 这个fact 对象有什么意义?
【解决方案2】:

通过在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 是Older way to register event listeners。

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

var windowElem = angular.element($window);

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

请务必将$window 添加到工厂函数的可注入列表中。

【讨论】:

    猜你喜欢
    • 2019-08-06
    • 2014-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    相关资源
    最近更新 更多