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

时间:2013-10-22 19:45:37

标签: javascript angularjs knockout.js

我在我的项目中使用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”observable。如何使用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
    }
}

最佳做法是什么?

2 个答案:

答案 0 :(得分:12)

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

我们不是使用angular $ watch方法,而是设置fullName属性的原生javascript getter和setter:

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

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

答案 1 :(得分:0)

很抱歉。确实,这在敲除时更简单,因为调用函数而角色中使用属性。这是我解决问题的方法,但我想知道是否有更好的方法。

我这次修复了Plunker

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];  
    });
});