gpt4 book ai didi

Javascript 方法代理和 AngularJS

转载 作者:行者123 更新时间:2023-11-28 07:20:59 25 4
gpt4 key购买 nike

我正在使用 AngularJS,在访问相同的基于方法的变量时,即 {{someValue()}},我意识到每次通过 $apply 刷新作用域时都会调用该方法。由于我的方法是确定性的,即仅取决于我知道的少数输入,我如何制作代理以避免多次处理相同的数据?

最佳答案

[更新]我最近发现了 memoize(understore 和 lodash)功能,其作用类似:https://lodash.com/docs#memoize

下面是我之前的回答:

我解决了构建 MethodProxy 对象的问题

  1. MethodProxy 将回调作为参数(代理的方法)

  2. 我们通过代理调用方法,如果参数严格相同,代理将返回缓存的结果,否则将使用回调更新其值,存储并返回结果。

注意:以下解决方案使用 _.isEqual 比较参数,该参数包含 UnderscoreJS 的一部分或Lodash如果您需要一个缓慢的(大约 3 times slower )但临时的比较器,只需定义

_ = {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()}}

限制:该方法必须是确定性的,即在给定输入参数的情况下应始终给出相同的输出如果参数很大,可能需要一些时间来比较它们。

其他:您可以从函数本身捕获值,只需将用于检查它们是否更改的相关参数发送到调用方法。

关于Javascript 方法代理和 AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30326392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com