[英]Javascript method proxy and AngularJS
我正在使用AngularJS,并且在访问基于方法的同一变量(即{{someValue()}}
,我意识到每次通过$ apply刷新范围时都会调用该方法。 由于我的方法是确定性的,即仅依赖于我知道的很少的输入,我如何制作代理以避免多次处理相同的数据?
[更新]我最近发现了备忘(understore和lodash)功能,其功能类似: https ://lodash.com/docs#memoize
在我以前的答案下面:
我解决了构建MethodProxy对象的问题
MethodProxy将回调作为参数(代理方法)
我们通过代理调用该方法,如果参数严格相同,则代理将返回缓存的结果,否则它将使用回调更新其值,存储并返回结果。
注意:以下解决方案比较了使用的参数_.isEqual
这需要的部分UnderscoreJS或Lodash如果你需要一个缓慢的(近似3倍慢 ),但暂时比较只是定义
_ = {isEqual:function(a,b){return JSON.stringify(a)===JSON.stringify(b)}};
但是再次,我强烈建议您使用经过优化的Lodash,这是MethodProxy:
function MethodProxy(callback_)
{
var lastArguments = undefined;
var callback = callback_;
var cachedAnswer = undefined;
this.call = function()
{
if (_.isEqual(lastArguments, arguments))
{
return cachedAnswer;
}
else
{
lastArguments = arguments;
cachedAnswer = callback.apply(this, arguments);
return cachedAnswer;
}
};
}
用法示例:
var test = new MethodProxy(function(value)
{
console.log("The method is called");
return value;
})
test.call("hello");// prints "The method is called" then return "hello"
test.call("hello");// returns "hello" (the cached value)
test.call("world");// prints "The method is called" then return "world"
如何在angular内使用它?
在JS中:
function myDataProxy = new MethodProxy(function(arg1, arg2)
{
// your expensive CPU method
return arg1+arg2;
})
$scope.myData = function()
{
var value1 = $scope.valueWhichCanChangeOrNot;
var value2 = $scope.anotherValueWhichCouldHaveBeenUpdated;
return myDataProxy.call(value1, value2);
}
在HTML中:
{{myData()}}
局限性:该方法必须是确定性的,即在给定其输入参数的情况下应始终提供相同的输出。如果参数很大,则可能需要花费一些时间进行比较。
其他:您可以从函数本身捕获值,只有相关参数(用于检查它们是否已更改)需要发送到调用方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.