I recently came to understand that Javascript operates on a "Call by sharing" principle, which means that everything is passed by value but the original contents of an object can still be modified. To illustrate this concept, consider the following scenario:
function changeObjectProperties(obj) {
obj.p = 20;
}
var obj = { p: 10; }
changeObjectProperties(obj);
console.log(obj.p); // outputs 20 because it's been changed!
This realization led me to wonder if Angular could leverage this mechanism to monitor variables without relying on $scope.$watch. Surprisingly, it turned out to work quite well.
controllers.js:
.controller('Listener', function($scope, UserService) {
$scope.user = UserService.getUser();
})
.controller('Changer', function($scope, UserService) {
// let's say there's a button in the UI that updates the email address
$scope.buttonClick = function() {
UserService.setEmail('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="16707979567477643875797b">[email protected]</a>');
}
});
services.js:
.factory('UserService', function() {
var user = {
name: 'Foo',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2c7dac3cfd2cec7e2c7dac3cfd2cec78cc1cdcf">[email protected]</a>'
};
return {
getUser: function() { return user; },
setEmail: function(email) { user.email = email; }
};
});
The $scope.user
variable inside the Listener
controller gets updated whenever the user clicks the button in the Changer
controller. If this variable is displayed in the HTML, the change will be visible.
The main drawback is that the object itself cannot be altered, as updating the object reference would disconnect the Listener
controller from the correct reference.
I tried searching for information on whether this approach is commonly used and considered good practice, but I couldn't find much. Perhaps I'm not using the right terminology. So, are people actually utilizing this technique? Is it deemed a best practice or are there potential pitfalls I should be aware of?