Javascript方法代理和AngularJS
我使用的是AngularJS,在访问相同的基于方法的变量时,即Javascript方法代理和AngularJS,javascript,angularjs,proxy-classes,Javascript,Angularjs,Proxy Classes,我使用的是AngularJS,在访问相同的基于方法的变量时,即{{someValue()}},我意识到每次通过$apply刷新作用域时都会调用该方法。由于我的方法是确定性的,即只依赖于我知道的几个输入,我如何制作代理以避免多次处理相同的数据?[UPDATE] 我最近发现了memoize(understore和lodash)函数,其作用类似于: 以下是我先前的回答: 我解决了构建MethodProxy对象的问题 MethodProxy将回调作为参数(代理的方法) 我们通过代理调用该方法,如果参数完
{{someValue()}}
,我意识到每次通过$apply刷新作用域时都会调用该方法。由于我的方法是确定性的,即只依赖于我知道的几个输入,我如何制作代理以避免多次处理相同的数据?[UPDATE]
我最近发现了memoize(understore和lodash)函数,其作用类似于:
以下是我先前的回答:
我解决了构建MethodProxy对象的问题
.isEqual
来比较参数,如果您需要一个缓慢(近似)但临时的比较器,则只需定义一个
_ = {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"
如何使用它的角度
在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()}}
限制:
该方法必须是确定性的,即在给定其输入参数的情况下,应始终提供相同的输出
如果争论很大,可能需要一些时间进行比较
其他:
您可以从函数本身捕获值,只需将相关参数发送到调用方法,以检查这些参数是否已更改