Why does binding trigger a $watch although no data was changed? - angularjs

I have an entity in the scope that is being edited by the user. Each time it gets modified, I want to trigger some custom validation. So I have:
// validate the position if anything has changed
$scope.$watch("entity", function() {
if ($scope.entity.Id) {
$scope.validate();
}
}, true /* watch "by value" (see: https://docs.angularjs.org/guide/scope#scope-life-cycle) */);
So far so good. Now, since this is a big entity with quite some fields, not all of the fields participate initially in data-binding. Only portions of the fields are visible to the user by using a tab control. When the user switches tabs, another portion of the entity is shown.
However, when the additional controls get bound to the corresponding fields of the entity, the $watch gets triggered even though the binding doesn't change any value on the entity.
Why is this the case and how could I prevent it?
Note:
I thought that the data-binding is possibly adding some internal $... fields to entity but these are hopefully disregarded (at least this is the case in angular.equals so they should probably be disregarded in the $watch too, I assume).

$watch with object equality flag true compares the properties of the old object copy with the current object. Therefore the listener fires when a property name is changed, added, or removed. You can try something like the following:
$scope.$watch("entity", function(newVal, oldVal) {
if(Object.keys(newVal).length !== Object.keys(oldVal).length)
return; //Detect added properties
if ($scope.entity.Id) {
$scope.validate();
}
}, true

Related

AngularJS fire change event when model updated programmatically

The fact that ng-change is only for user input, and does not fire when changes are made to the model programmatically, is really causing me a headache today. I'm working with a user input form which has the separate parts of a name, as well as dynamically built and ordered credentials. The form has a "displayName" field that gets updated when the name parts are changed. This is encapsulated in a directive which I need to use in a larger view. Here's where things get hairy. I need to hide the name part fields in my directive and use the outer form's name fields. I thought this would be easy by wiring up a function to update the hidden text input fields, and thus my displayName field. Then I found out programmatic changes to the model do not fire the change event.
I tried creating a watch for one of the name fields to see if I could get it to update the displayName field, but no luck.
this.scope.$watch('provider.firstName', function (event) {
namePropertyChanged2(displayNameOverridden, displayName, provider, credentials);
});
When I change the input field for firstName, it modifies the directive's value 'provider.firstName', and runs the 'namePropertyChanged2' function. The code listed runs in an initialize function, where 'displayName' is a local variable assigned from this.scope.provider.displayName. The watch assignment required me to make local variables instead of passing in controller variables. Not sure why, but whatever. So this function runs and 'displayName' is updated with the correct value... and the input field it's bound to is not updated. Bummer.
What would be ideal is to manually trigger the change event when the model changes, which would update the displayName and much rejoicing to be had.

triggering $onChanges for updated one way binding

I'm really happy with the "new" $onChanges method you can implement in a component's controller. However it only seems to be triggered when the bound variable is overwritten from outside my component, not (for instance) when an item is added to an existing array
It this intended behaviour or a bug? Is there another way of listening to updates to my input bindings, besides doing a $scope.$watch on it?
I'm using Angular 1.5.3
First TL;DR
For an array that is bounded via one-way binding, a watch expression is added that does not check for object equality but uses reference checking. This means that adding an element to the array will never fire the '$onChanges' method, since the watcher will never be 'dirty'.
I've created a plnkr that demonstrates this:
http://plnkr.co/edit/25pdLE?p=preview
Click the 'add vegetable in outer' and 'change array reference in outer' and look at the 'Number of $onChanges invocation'. It will only change with the latter button.
Complete explanation
To fully grasp what is going on, we should check the angular code base. When a '<' binding is found, the following code is used to set up a watch expression.
case '<':
if (!hasOwnProperty.call(attrs, attrName)) {
if (optional) break;
attrs[attrName] = void 0;
}
if (optional && !attrs[attrName]) break;
parentGet = $parse(attrs[attrName]);
destination[scopeName] = parentGet(scope);
// IMPORTANT PART //
removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newParentValue) {
var oldValue = destination[scopeName];
recordChanges(scopeName, newParentValue, oldValue);
destination[scopeName] = newParentValue;
}, parentGet.literal);
// ------------- //
removeWatchCollection.push(removeWatch);
break;
The important part here is how the 'scope.$watch' expression is set up. The only parameters passed are the parsed expression and the listener function. The listener function is fired once the '$watch' is found dirty in the digest cycle. If it is fired, the listener will execute the 'recordChanges' method. This records an '$onChanges' callback task that will be executed in the '$postDigest' phase and notify all components that are listening for the '$onChanges' lifecycle hook to tell them if the value has changed.
What's important to keep in mind here, if the '$watcher' is never dirty, the '$onChanges' callback is not triggered. But even more importantly, by the way the '$watch' expression is created, it will NEVER be dirty, UNLESS the reference changes. If you wanted to check for equality between objects instead of reference, you should pass an extra third parameter that asks for this:
$watch: function(watchExp, listener, objectEquality, prettyPrintExpression)
As this is not the case here with the way the one way binding is set up, it will ALWAYS check for reference.
This means, if you add an element to an array, the reference is not changed. Meaning the '$watcher' will never be dirty, meaning the '$onChanges' method will not be called for changes to the array.
To demonstrate this, I've created a plnkr:
http://plnkr.co/edit/25pdLE?p=preview
It contains two components, outer and inner.
Outer has primitive string value that can be changed through an input box and an array that can be extended by adding an element or have its reference changed.
Inner has two one-way bounded variables, the value and the array. It listens for all changes.
this.$onChanges = setType;
function setType() {
console.log("called");
vm.callCounter++;
}
If you type into the input field, the '$onChanges' callback is fired every time. This is logical and expected, since a string is primitive so it cannot be compared by reference, meaning the '$watcher' will be dirty, and the '$onChanges' lifecycle hook fired.
If you click the 'Add vegetable in outer', it will execute the following code:
this.changeValueArray = function() {
vm.valueArray.push("tomato");
};
Here we just add a value to the existing bounded array. We're working by reference here, so the '$watcher' is not fired and there is no callback. You will not see the counter increment or the 'called' statement in your console.
Note: If you click the 'Add something to the array' inside the inner component, the array in outer component also changes. This is logical, since we are updating the exact same array by reference. So even though it is a one-way binding, the array can be updated from inside the inner component.
If you change the reference in the outer component by clicking 'Change array reference in outer', the '$onChanges' callback is fired as expected.
As to answer your question: Is this intended behaviour or a bug? I guess this is intended behaviour. Otherwise they would have given you the option to define your '<' binding in a way that it would check for object equality. You can always create an issue on github and just ask the question if you'd like.

HasChanged Not Working in Backbone 1.1.2

CodePen: http://codepen.io/opnsrce/pen/hclaH
Expected behavior: You should only be able to highlight one item at a time.
Current Behavior: You can highlight multiple items
Cause: HasChanged returns true when checked by the controller during the change event.
When I run this code with Backbone 0.9.2 it works. When I use 1.1.2 it doesn't.
Did something fundamentally change in the way hasChanged works between those two versions?
I believe this is the desired functionality. A model's changed attributes change each time the model itself is set. So until you set a model multiple times it will hold onto its changes. The code you've set up here would work if that hash of changes cleared out when a different model was selected. What is actually happening is that as soon as you set a model to isSelected it will always have isSelected == true and hasChanged('isSelected'), so it will never pass the condition to set isSelected to false.
One way to accomplish what you're looking for is to change your collection method to this:
onSelectedChanged: function(modelActive) {
if(modelActive.get('isSelected') === true){
this.each(function(model) {
if (model != modelActive) {
model.set({isSelected: false});
}
});
}
}
Note that I took out hasChanged since that was simply confirming that a model had changed at some previous point. Instead I compare the actively selected model with the ones being iterated. We don't want to touch the active one. I also check to see if this method was triggered via the setting of isSelected to true because if we don't do that, every setting of the iterated models to false will trigger this method and cause problems.
The only limitation of this is that you can't select the same item to toggle it off.

Stickit: How to trigger a change event after every model -> view change

I have many events bound to elements in my view, though when I use stickit js to change values in my view by altering the model it doesn't trigger an onChange event.
Is there a way that I can trigger an onchange event for the current model:element after the setting the value in the model without having to write a handler for every binding? This would be for all form elements, input/select/textarea.
I want to avoid the following for each form element on the page:
bindings: {
'#foo': {
observe: 'foo',
afterUpdate: 'forceChange'
},
'#bar': {
observe: 'bar',
afterUpdate: 'forceChange'
},
...
},
forceChange: function(el) { jQuery(el).change() }
One possible hack (with version 0.6.3 only) would be to define a global handler which matches all elements:
Backbone.Stickit.addHandler({
selector: '*',
afterUpdate: function($el) {
$el.trigger('change');
}
});
Since handlers are mixed in with other matching handlers and bindings configurations in the order that they are defined, you couldn't use afterUpdate in any of your bindings without overwriting this global, all-matching handler since the bindings configurations are the last to be mixed in. You can read more about it here.
Ahhh, that comment clarifies matters. So, in Javascript when you change an input's value "manually" (whether through jQuery or through someElement.value =) the browser won't, as you noticed, fire a change event. Change events (and most other events for that matter) are only fired in response to user actions, not to Javascript.
Luckily, just as you can "manually" change a value, you can also "manually" trigger an event. In jQuery the syntax for that is:
$(yourElement).trigger('change');
If you need to control things like e.target you can read up on the jQuery trigger documentation for the details, but that's the basic idea.
You can even chain the value-changing and event-triggering together if you want:
$(yourElement).val('newValue').trigger('change');

Understanding Backbone Model set, validate and change callbacks

The Backbone documentation says:
Model.set will fail if validation fails - it won't set the value therefore it won't trigger any callback. We can pass { silent: true } to Model.set - then it will set the value but won't trigger any callback neither.
So,
Why does Backbone Model require a valid state to simply set an attribute value? What if we want to set attributes as the user interacts with the UI, but the model is not valid yet? It means change callbacks are unavailable unless we pass { silent: true } then manually trigger the change?!
Please say you know a better way of handling this :)
I'm not sure how to answer the Why questions but you could say that there are arguments for why it is good that set runs validations. For instance, it makes it dead simple to do client side validation in real time.
If your problem could be solved by only validating the value that is currently being changed by the user, you can do that by combining your validate method with the hasChanged method.
For example something like this:
Backbone.Model.extend({
defaults : { name : "" },
validate : function (attrs) {
var errors = {};
if(this.hasChanged("name") && attr.name.length == 0) {
errors.name = "Need a name yo!";
}
//...
if(_.keys(errors).length > 0) {
return errors;
}
}
})
In Backbone whenever you call set on model , It keeps track of what attributes of model has been changed and what attributes are newly added.Calling validate allows it be more efficient in doing it .Passing {silent:true} as options in set function causes validate and change to not execute so if doesnt fire any change events.
If you want to set attributes as the user interacts with the UI, but the model is not valid yet
In this case you can set the change in a plain object make sure object keys are sames as model's attribute and then at some point just set in your model.
var uiChanges = {name:'x'}; //just fill it with your changes
ur_model.set(uiModel); //then set it ,this way it fires change events only once
To check the diff between your plain object and model you can use the
ur_model.changedAttributes(uiChanges);
changedAttributes -
Return an object containing all the attributes that have changed, or false if there are no changed attributes.
You can further use it save only those attributes that have changed rather than saving entire model again.

Resources