Watch all elements of an object except one - angularjs

I have a watch in my code
scope.$watch(foo, function () {
...
}, true);
This ensures that if any attribute in the object foo changes then this watch will be called. I want to make an exception to this. I want to call this watch if any attribute in foo changes except one. If that attribute changes this watch should not be called. How is this possible?

I can think of 2 different ways to do this:
Option 1, just handle it at the beginning of your $watch function:
scope.$watch(foo, function (newVal, oldVal) {
if(newVal.propertyThatYouDontWantToWatch === oldVal.propertyThatYouDontWantToWatch)
return;
/* Normal Code here*/
}, true);
Option 2, define the property that you don't want to watch like this (I'm pretty sure that this option won't trigger the $watch of your foo object):
Object.defineProperty(
foo,
'propertyThatYouDontWantToWatch',
{
enumerable:false,
configurable:true,
writable: true,
value:{} /*Replace {} with the value that you want to assign to your property*/
}
);

Related

Angularjs: Watch object and compare to original object

I have a vm with two objects in it:
vm.obj = {
intObj1: {
title: 'title1'
},
intObj2: {
name: 'name1'
}
}
The vm.obj is bound to the view (I am using the controller as syntax)
I want to have the original data so I cloned the model using lodash:
var originalModelState = _.cloneDeep(vm.obj);
I am watching for changes in the model compared to the original state:
$scope.$watch('vm.obj', function(newValue, oldValue){
if (newValue !== originalModelState){
}
}, true);
Sadly newValue !== originalModelState is always different, which is expected as the references are different. I tried also comparing newValue with oldValue but the issue there is that if the user changes a property for example: vm.obj.intObj1.title = 'new title' and then change back to the original value `vm.obj.intObj1.title = 'title1' I cannot detect that the vm is the same as the original value. How can I do this ?
Have you considered
var originalModelState = JSON.stringify(vm.obj);
...
if (JSON.stringify(newValue) != originalModelState){
}
Comparing objects as strings is imho a very effective and easy way to spot differences, especially when you not know what to look for.
Not sure, if I understood correctly what you wanted to ask. The watcher callback is only executed, if something in your object has changed. The 'true' performs a deep watch.
If you only want to know, if the value deep in your object is equal to the originial value on the same position, you could check in the watcher:
$scope.$watch('vm.obj', function(newValue){
if (originalModelState.intObj1.title === newValue.intObj1.title) {
// do something
}
}, true);

AngularJS watch model value if model is not null

Simple question here.
I have this watch:
// Watch our model
$scope.$watch(function () {
// Watch our team name
return self.model.team.data.name;
}, function (name) {
console.log(name);
// if we have a name
if (name) {
// Store our model in the session
sessionStorage.designer = angular.toJson(self.model);
}
});
The team model is pull in from the database as a promise (hence the data) so when the watch first fires self.model.team has not been set so it is null.
How can I get my watch to either wait until it has been set or add a check into the return function of the watch?
Use a watch expression instead of a function. This will catch any errors with missing objects and return undefined.
// Watch our model
$scope.$watch('self.model.team.data.name', function (name) {
console.log(name);
// if we have a name
if (name) {
// Store our model in the session
sessionStorage.designer = angular.toJson(self.model);
}
});
There is no magic here - if one of the variables you are accessing could be null/undefined, then you cannot get its property if it's null/undefined. So, you have to guard against that:
$scope.$watch(
function(){
return (self.model.team && self.model.team.data.name) || undefined;
},
function(v){
// ...
});
The only "magic" is when you "$watch" for expressions, but the expressions need to be exposed on the scope. So, you could do:
$scope.model = self.model;
$scope.$watch("model.team.data.name", function(v){
// ...
});
But, really, you have to ask yourself why you need a $watch here to begin with. It seems to me that you are getting the team asynchronously once - it does not look like it will change except by maybe another async call. So, just handle that when you receive the data without the $watch:
someSvc.getTeam() // I made an assumption about a service that pulls the data from db
.then(function(team){
var name = team.data.name;
// if we have a name
if (name) {
// Store our model in the session
sessionStorage.designer = angular.toJson(self.model);
}
});
An unnecessary $watch is expensive - it is evaluated on every digest cycle, so, it's best to reduce the number of $watchers.

angular watch on object and it's child

I have an on object in my directive, let's say:
scope = {
A : {
B : [],
C : 5
}
}
scope.$watch('A', function aWasChanged(){});
scope.$watchCollection('B', function bWasChanged(){});
I have a watch on A and on B. But when A is changed the watch of B is called as well. What I want is that when A is changed only "aWasChanged" will be called (even if B was changed as well) and "bWasChanged" will be called only when B is changed.
What do you mean under A is changed.
Generally the $watch() only checks object reference equality but not structure.
For example if you will write something like:
$scope.A.ddd = "ddd";
the $watch will do not catch that.
However deep-watch (with flag true) should take care about this case.
when A is changed only "aWasChanged" will be called...
I suppose you mean if C will change ... so write your custom comparator like:
$scope.$watch(function () {
return $scope.A;
},
function (newValue, oldValue) {
if(newValue.C == oldValue.C){return;} // avoid B
/*...*/
}, true); // Object equality (not just reference).
The deep-watch a bit expensive so like you wrote will be good way:
scope.$watchCollection('A.B', function bWasChanged(){});
If you really wanted to do something like
$scope.foo.A = {
B: [],
C: 6
};
and have the watch on A fire but not on the B fire, you could always hack how angular is indexing it.
var key = $scope.foo.A.B.$$hashKey;
$scope.foo.A = {
B: [],
C: 6
};
$scope.foo.A.B.$$hashKey = key;
Here is an updated plnkr with that http://plnkr.co/edit/hAY9pb3AUAF0drAm42A5?p=preview.

need help to understand angular $watch

say I have a album list and user can add album
controller.albumList = function($scope, albumService) {
$scope.albums = albumService.query();
$scope.$watch('$scope.albums',function(){
$scope.albums.$save($scope.albums)
})
$scope.addalbum= function(){
$scope.albums.objects.push(album);
}
};
get a album list from server and show them
user can add album
watch the albums list ,when change happend save them to the server.
the problem is the $watch always fired, I did not even trigger the addalbum method, and every time I refresh the page a new album is created.
I follow the the code in todeMVC angular
here is the example code
var todos = $scope.todos = todoStorage.get();
$scope.newTodo = '';
$scope.editedTodo = null;
$scope.$watch('todos', function () {
$scope.remainingCount = filterFilter(todos, { completed: false }).length;
$scope.completedCount = todos.length - $scope.remainingCount;
$scope.allChecked = !$scope.remainingCount;
todoStorage.put(todos);
}, true);
please help me understand this
this is a solution:
$scope.$watch('albums', function(newValue, oldValue) {
if (angular.equals(newValue, oldValue)) {
return;
}
$scope.albums.$save($scope.albums);
}
After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. To detect this scenario within the listener fn, you can compare the newVal and oldVal. If these two values are identical (===) then the listener was called due to initialization.
More about a $watch listener: $watch at angularjs docs
Firstly, you do not have to specify the scope object when referencing to a property of the scope. So, replace:
$scope.$watch('$scope.albums', ...)
with the following:
$scope$watch('albums', ...)
Now about your issue. $watch is triggered each time the value of the object / property being watched changes. This includes even those cases when the values are yet to be assigned, such as undefined and null. Thus, if you wish that the save should happen only when a new album is added, you can have code similar to:
//Makes assumption that albums has a length property
$scope.$watch('albums.length', function () {
//Check for invalid cases
if ($scope.albums === undefined || $scope.albums === null) {
return;
}
//Genuine cases.
//Proceed to save the album.
});
With this, the $watch is still triggered in unwanted scenarios but with the check, you avoid saving when the album has not changed. Also, note that your $watch triggers only when the length of the albums object changes. So, if an album itself is updated (say an existing album name is changed), then this watch is not triggered. You can change the watch property based on your needs. The watch property mentioned here works only when a new album is added.

Backbone: validating attributes one by one

I need to validate a form with a bunch of inputs in it. And, if an input is invalid, indicate visually in the form that a particular attribute is invalid. For this I need to validate each form element individually.
I have one model & one view representing the entire form. Now when I update an attribute:
this.model.set('name', this.$name.val())
the validate method on the model will be called.
But, in that method I am validating all the attributes, so when setting the attribute above, all others are also validated, and if any one is invalid, an error is returned. This means that even if my 'name' attribute is valid, I get errors for others.
So, how do I validate just one attribute?
I think that it is not possible to just validate one attribute via the validate() method. One solution is to not use the validate method, and instead validate every attribute on 'change' event. But then this would make a lot of change handlers. Is it the correct approach? What else can I do?
I also think that this points to a bigger issue in backbone:
Whenever you use model.set() to set an attribute on the model, your validation method is run and all attributes are validated. This seems counterintuitive as you just want that single attribute to be validated.
Validate is used to keep your model in a valid state, it won't let you set an invalid value unless you pass a silent:true option.
You could either set all your attributes in one go:
var M=Backbone.Model.extend({
defaults:{
name:"",
count:0
},
validate: function(attrs) {
var invalid=[];
if (attrs.name==="") invalid.push("name");
if (attrs.count===0) invalid.push("count");
if (invalid.length>0) return invalid;
}
});
var obj=new M();
obj.on("error",function(model,err) {
console.log(err);
});
obj.set({
name:"name",
count:1
});
or validate them one by one before setting them
var M=Backbone.Model.extend({
defaults:{
name:"",
count:0
},
validate: function(attrs) {
var invalid=[];
if ( (_.has(attrs,"name"))&&(attrs.name==="") )
invalid.push("name");
if ( (_.has(attrs,"count"))&&(attrs.count===0) )
invalid.push("count");
if (invalid.length>0) return invalid;
}
});
var obj=new M();
obj.on("error",function(model,err) {
console.log(err);
});
if (!obj.validate({name:"name"}))
obj.set({name:"name"},{silent:true});
I recently created a small Backbone.js plugin, Backbone.validateAll, that will allow you to validate only the Model attributes that are currently being saved/set by passing a validateAll option.
https://github.com/gfranko/Backbone.validateAll
That is not the issue of Backbone, it doesn't force you to write validation in some way. There is no point in validation of all attributes persisted in the model, cause normally your model doesn't contain invalid attributes, cause set() doesn't change the model if validation fails, unless you pass silent option, but that is another story. However if you choose this way, validation just always pass for not changed attributes because of the point mentioned above.
You may freely choose another way: validate only attributes that are to be set (passed as an argument to validate()).
You can also overload your model's set function with your own custom function to pass silent: true to avoid triggering validation.
set: function (key, value, options) {
options || (options = {});
options = _.extend(options, { silent: true });
return Backbone.Model.prototype.set.call(this, key, value, options);
}
This basically passes {silent:true} in options and calls the Backbone.Model set function with {silent: true}.
In this way, you won't have to pass {silent: true} as options everywhere, where you call
this.model.set('propertyName',val, {silent:true})
For validations you can also use the Backbone.Validation plugin
https://github.com/thedersen/backbone.validation
I had to make a modification to the backbone.validation.js file, but it made this task much easier for me. I added the snippet below to the validate function.
validate: function(attrs, setOptions){
var model = this,
opt = _.extend({}, options, setOptions);
if(!attrs){
return model.validate.call(model, _.extend(getValidatedAttrs(model), model.toJSON()));
}
///////////BEGIN NEW CODE SNIPPET/////////////
if (typeof attrs === 'string') {
var attrHolder = attrs;
attrs = [];
attrs[attrHolder] = model.get(attrHolder);
}
///////////END NEW CODE SNIPPET///////////////
var result = validateObject(view, model, model.validation, attrs, opt);
model._isValid = result.isValid;
_.defer(function() {
model.trigger('validated', model._isValid, model, result.invalidAttrs);
model.trigger('validated:' + (model._isValid ? 'valid' : 'invalid'), model, result.invalidAttrs);
});
if (!opt.forceUpdate && result.errorMessages.length > 0) {
return result.errorMessages;
}
}
I could then call validation on a single attribute like so
this.model.set(attributeName, attributeValue, { silent: true });
this.model.validate(attributeName);

Resources