【问题标题】:$timeout use inside AngularJS factory$timeout 在 AngularJS 工厂中使用
【发布时间】:2016-09-10 02:23:29
【问题描述】:

我使用 AngularJS 工厂为我的项目创建了新的实例模型,每个模型都包含一个进度值,该值将根据“开始”、“暂停”和“停止”用户进行递增、暂停和设置回 0行动。

app.factory('ModelA', ['$timeout', function($timeout) {
    function ModelA(progress) {
        this.progress = progress;
    };

    ModelA.prototype = {
        startProgress: function() {
            this.counterFunction();
        },
        counterFunction: function() {
            this.progress++;
            if(this.progress == 100) {
                this.progress = 0;
            }
            //console.log(this.progress);
            //console.log(this.counterFunction);
            progressTimeout = $timeout(this.counterFunction, 1000);
        },
        // Haven't tested the method below
        pauseProgress: function() {
            $timeout.cancel(progressTimeout);
        },
        stopProgress: function() {
            $timeout.cancel(progressTimeout);
            this.progress = 0;
        }
    };
    return ModelA;
}]);

由于某种原因,当我在ng-click表达式函数中调用startProgress()时,进度会增加1然后停止。我添加了日志以检查每个呼叫的this.counterFunction。我意识到它只会在第一次打印出1 和整个counterFunction。至于第二次,this.progress 将变为NaN,counterFunction 将显示undefined

我是 AngularJS 的新手,有人可以帮帮我吗?谢谢。

【问题讨论】:

  • 如果以后有人遇到此问题,我建议您查看@BrianHsu 和 Lihau Tan 发布的两个答案,以帮助您更好地理解setTimethis 主题。

标签: javascript angularjs factory


【解决方案1】:

$timeout调用的函数中的this对象,即this.counterFunciton不是ModelA实例,所以你应该使用 $timeout(this.counterFunction.bind(this), 1000) 代替。

您可以阅读此 article 关于在 JavaScript 中绑定 this 对象的信息。

一个有效的codepen 供您参考。

【讨论】:

    【解决方案2】:

    执行上下文this 会在 $timeout 被执行时发生变化。您需要在 $timeout(this.counterFunction.bind(this), 1000) 中保留 ModelA this。您将this 绑定并传递给this.counterFunction,因此counterFunction 有权访问this.progress。

    在此处查看有关this 问题的更多信息。 $timeout 是 window.setTimeout 的包装 https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout#The_this_problem

    【讨论】:

    • 感谢您的回答和文章!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    • 2014-11-24
    • 1970-01-01
    • 2014-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多