I recently 'discovered' that Javascript is a "Call by sharing" (wikipedia explanation) language, meaning that in essence, everything is passed by value however the original contents of an object can still be changed. A quick example:
function changeObjectProperties(obj) {
obj.p = 20;
}
var obj = { p: 10; }
changeObjectProperties(obj);
console.log(obj.p); // will print 20; it's changed!
This made me wonder if this can be used within Angular to 'watch' variables without using $scope.$watch. The following works.
controllers.js:
.controller('Listener', function($scope, UserService) {
$scope.user = UserService.getUser();
})
.controller('Changer', function($scope, UserService) {
// let's imagine the UI has some button that changes the e-mailadres
$scope.buttonClick = function() {
UserService.setEmail('foo@bar.com');
}
});
services.js:
.factory('UserService', function() {
var user = {
name: 'Foo',
email: 'example@example.com'
};
return {
getUser: function() { return user; }
setEmail: function(email) { user.email = email; }
};
});
The $scope.user
variable within the Listener
controller is updated when the user clicks the button within the Changer
controller. This change is visible would this variable be displayed in the HTML.
The most obvious pitfall of course is that the object itself can not be changed, as the object reference is then changed and the Listener
controller is listening to the wrong reference.
I've searched around to find if this is being done and if its considered good coding. I haven't been able to find anything, possibly because I don't know the correct terms to use. So, is this technique actively being used? Is it considered a good practice or is there some pitfall I'm not aware of?