StackOverflow_25055589: object-observe-synchronous-callback

Illustration of answer to http://stackoverflow.com/questions/25055589/object-observe-synchronous-callback.

by ExpertSystem

HTML

<script src="http://code.angularjs.org/1.2.21/angular.min.js"></script>
<div ng-controller="mainCtrl">
    <label>Firstname: <input type="text" ng-model="p.firstname" /></label><br />
    <label>Lastname:  <input type="text" ng-model="p.lastname" /></label>
    <hr />
    Fullname: {{p.fullname}}
</div>

<!-- -=-=-=-=- -=-=-=-=- -=-=-=-=- -=-=-=-=- -=-=-=-=- -->
<!-- Page Footer -->
<small class="footer" ng-controller="footerCtrl">
    <b>Angular v{{version.full}}</b> ({{version.codeName}})
    <span class="right">
        &copy; <a ng-href="{{authorUrl}}" target="_blank">ExpertSystem</a>
    </span>
</small>

CSS

/* -=-=-=-=- -=-=-=-=- -=-=-=-=- -=-=-=-=- -=-=-=-=- */
/* Page Footer */
body { padding-bottom: 22px; }
.footer { background-color: White; border-top: 1px solid rgba(100, 100, 100, 0.33); bottom: 0; display: block; font-size: 0.75em; height: 20px; left: 0; margin: 0 10px; overflow: auto; padding: 5px 0; position: fixed; right: 0; }
.right { float: right; }

JavaScript

var app = angular.module('myApp', []);
    app.controller('mainCtrl', function ($scope, Person) {
        $scope.p = new Person('Alice', 'Rogers');
        $scope.p.watch();
        $scope.p.firstname = 'Bob';
    });

    app.factory('Person', function ($rootScope) {
        return function Person(firstname, lastname) {
            var self = this;
    
            self.firstname = firstname;
            self.lastname  = lastname;
            self.fullname  = firstname + ' ' + lastname;
    
            this.watch = function () {
                Object.observe(self, function (changes) {
                    $rootScope.$apply(function () {
                        changes.forEach(function (change) {
                            console.log(change);
                            if (change.name === 'firstname' ||
                                    change.name === 'lastname') {
                                self.fullname = self.firstname + ' ' + self.lastname;
                            }
                        });
                    });
                });
            };
        };
    });

/* -=-=-=-=- -=-=-=-=- -=-=-=-=- -=-=-=-=- -=-=-=-=- */
/* Page Footer */
app.controller('footerCtrl', function ($scope) {
    $scope.authorUrl = '//stackoverflow.com/users/2341938/expertsystem';
    $scope.version   = angular.version;
});