Knockout的可写计算在AngularJS中可观察的模拟是什么?

What is the analog for Knockout's writable computed observable in AngularJS?

本文关键字:观察 模拟 是什么 计算 Knockout AngularJS      更新时间:2023-09-26

我在项目中使用KnockoutJS,但想学习AngularJS,因为它有很多Knockout没有的美味功能。所以我有兴趣使用 Angular 重写我的一些代码。但是我不明白如何做我在Knockout中使用的一些简单的事情。例如,Knockout 具有计算可观察量的功能。太酷了!我已经发现我可以使用一个简单的函数来代替。但是 Knockout 为计算的可观察量提供了"写入"功能,例如:

var first_name = ko.observable('John'),
    last_name = ko.observable('Smith'),
    full_name = ko.computed({
        read: function(){
            return first_name() + ' ' + last_name();
        },
        write: function(new_value){
            var matches = new_value.match(/^('w+)'s+('w+)/);
            first_name(matches[1]);
            last_name(matches[2]);
        }
    });

JSFiddle 上的这段代码:http://jsfiddle.net/Girafa/QNebV/1/

此代码允许我在更改"full_name"可观察量时更新"first_name"和"last_name"可观察量。如何使用AngularJS来完成?正在检查是否存在参数的函数?像这样的东西?

first_name = 'John';
last_name = 'Smith';
full_name = function(value){
    if (typeof value != 'undefined')
    {
        // do the same as in the Knockout's write function
    }
    else
    {
        // do the same as in the Knockout's read function
    }
}

最佳实践是什么?

我找到了这样的解决方案:http://jsfiddle.net/Girafa/V8BNc/

我们没有使用 angular $watch 方法,而是设置了 fullName 属性的本机 javascript getter 和 setter:

Object.defineProperty($scope, 'fullName', {
    get: function(){
        #...
    },
    set: function(newValue){
        #...
    }
})

认为这更方便,因为我不需要在代码中制作任何特殊的观察者。但我不知道此解决方案的浏览器支持。

对此感到抱歉。的确,这在挖空中更简单,因为调用函数而属性在角度中使用。这是我可以解决它的方法,但我想知道是否有更好的方法。

这次我修好了普伦克

app.controller('Ctrl', function($scope) {
    $scope.firstName = 'John';
    $scope.lastName  = 'Smith';
    $scope.getFullName = function() {
        $scope.fullName = $scope.firstName + ' ' + $scope.lastName;
        return $scope.fullName;
    }
    $scope.$watch('fullName', function(newValue, oldValue) {
        var names = newValue.split(' ');
        $scope.firstName = names[0];
        $scope.lastName  = names[1];  
    });
});