在范围/ $ scope / $ rootScope上创建$ interval的潜在问题

时间:2013-11-11 19:47:52

标签: angularjs

创建这样的东西会有什么问题(如果有的话):

scope.$interval = function(callback, duration){
    var internalScope = this;
    var interval = setInterval(function(){
        if(callback()){
            internalScope.$apply();
        }
    }, duration);
    internalScope.$on("$destroy", function(){
        clearInterval(interval);
    });
    return interval;
};

我必须运行我自己的$ apply,我理解但这样可以节省我在设置间隔时到处听取$ destroy事件。我也不熟悉扩展范围。如果我将它应用于$ rootScope,整个系统中的每个scope / $ scope是否都会继承该函数?

虽然很小,但会改变

var interval = setInterval(function(){

}, 100);
scope.$on("$destroy", function(){
    clearInterval(interval);
});

scope.$interval(function(){
    //return true to run the apply
}, 100);

作为另一个建议,使用$ timeout可以完成同样的事情:

scope.$timeout = function(callback, duration){
    var internalScope = this;
    var interval = setTimeout(function(){
        callback();
        internalScope.$apply();
    }, duration);
    internalScope.$on("$destroy", function(){
        clearTimeout(interval);
    });
    return interval;
};

导致

scope.$timeout(function(){

}, 100);

0 个答案:

没有答案