KO.Computed equivalent in Angular / Breeze Initializer

后端 未结 2 1853
别那么骄傲
别那么骄傲 2020-12-30 01:57

Trying to get a more in-depth understanding of how Angular treats data binding and understanding it better and one thing is difficult to get my head around -

In Kno

2条回答
  •  心在旅途
    2020-12-30 02:28

    I found the answer on the following website. If you don't do something similar, what you will find is that all functions are ran during the digest phase and are not triggered by the change of a dependent observable or property. The solution below allows you to only trigger the function when a value it uses is changed.

    http://www.jomendez.com/2015/02/06/knockoutjs-computed-equivalent-angularjs/

    Explains how to duplicate the subscribe and computed feature in knockoutjs

    var myViewModel = {
        personName: ko.observable('Bob')
    };
    myViewModel.personName.subscribe(function(oldValue) {
        alert("The person's previous name is " + oldValue);
    }, null, "beforeChange");
    

    This is what I found as result of my research (this is the AngularJs equivalent) Using the $scope.$watch method see the AngularJs life cycle https://docs.angularjs.org/guide/scope

    $scope.myViewModel = {
        personName: 'Bob'
    };
    $scope.$watch(‘myViewModel.personName’, function(newValue, oldValue){
        //we are able to have both the old and the new value
        alert("The person's previous name is " + oldValue);
    });
    
    //knockout computed
    var isVendorLoading = ko.observable(),
    isCustomerLoading = ko.observable(),
    isProgramLoading = ko.observable(),
    isWaiting = ko.observable();
    
    var isDataLoading = ko.computed(function () {
        return isVendorLoading() || isCustomerLoading() || isProgramLoading() || isPositionLoading() || isWaiting();     
    });
    

    This is the AngularJs Equivalent for KnockoutJs computed:

    $scope.isDataLoading = false;
    $scope.$watch(
        function (scope) {
            //those are the variables to watch
            return { isVendorLoading: scope.isVendorLoading, isCustomerLoading: scope.isCustomerLoading, isProgramLoading: scope.isProgramLoading, isWaiting: scope.isWaiting };
        },
        function (obj, oldObj) {
             $timeout(function () {
                  //$timeout used to safely include the asignation inside the angular digest processs
                  $scope.isDataLoading = obj.isVendorLoading || obj.isCustomerLoading || obj.isProgramLoading || obj.isPositionLoading || obj.isWaiting;
             });
        },
        true
    );
    

提交回复
热议问题