簡體   English   中英

Javascript方法代理和AngularJS

[英]Javascript method proxy and AngularJS

我正在使用AngularJS,並且在訪問基於方法的同一變量(即{{someValue()}} ,我意識到每次通過$ apply刷新范圍時都會調用該方法。 由於我的方法是確定性的,即僅依賴於我知道的很少的輸入,我如何制作代理以避免多次處理相同的數據?

[更新]我最近發現了備忘(understore和lodash)功能,其功能類似: https ://lodash.com/docs#memoize

在我以前的答案下面:

我解決了構建MethodProxy對象的問題

  1. MethodProxy將回調作為參數(代理方法)

  2. 我們通過代理調用該方法,如果參數嚴格相同,則代理將返回緩存的結果,否則它將使用回調更新其值,存儲並返回結果。

注意:以下解決方案比較了使用的參數_.isEqual這需要的部分UnderscoreJSLodash如果你需要一個緩慢的(近似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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM