$watch an Object using strict equality
See original GitHub issueWhat problem does this feature solve?
Hi,
I’d like to request a new option to the $watch() function that, in case of watching an instance of an Object or an Array, would make the watch callback be called only when the old instance is strictly unequal the new instance. This would offer an alternative to the current behaviour of always calling the watch callback when watching a non-primitive variable (as per the following comment).
The new option might be called something like: strictObjectComparison: boolean;
.
The use case is a situation when a dev knows exactly what they’re doing (i.e. watching an instance of a value object) and they want their watch callbacks to be called only if the instance changes.
This is somewhat related to this bug report: #6616. By adding the requested feature, the problem wouldn’t occur. Frankly, I’m also affected by this idiosyncrasy of the framework and would really appreciate if I could just tell the framework that I know what I’m doing and that I’d like the watched Object to be compared strictly (i.e. with ===
) and nothing more.
Thank you.
What does the proposed API look like?
class Person {
constructor(name) {
this.name = name;
}
}
const vm = new Vue({
data: {
people: [
new Person('Phil'),
new Person('Rob'),
new Person('Tom'),
],
selectedPerson: null,
}
});
vm.$watch(
'selectedPerson',
() => { console.log(vm.selectedPerson); },
{ strictObjectCompare: true }
);
// should trigger the watch callback
vm.selectedPerson = vm.people[0];
// should not trigger the watch callback
vm.selectedPerson = vm.people[0];
// should trigger the watch callback
vm.selectedPerson = vm.people[1];
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (4 by maintainers)
Top GitHub Comments
As said in the comment above, check between old and current value
Good day gentlemen,
Yes, this is not a double post, although both this ticket and #9837 touch the same ground but from different angle.
@posva suggested a solution to this ticket that I actually didn’t think of, but does solve this ticket’s problem. This means that we can close this ticket if we don’t want to take any action on its matter anymore.
To be honest, I’m in two minds now. I would appreciate a way to tell to the framework that I want to strict watch an object/array, but the solution that posva suggested is so simple and painless (although not immediately obvious, since watch callbacks should not be called when things don’t change) that it’s not worthwhile increasing the learning curve and maintenance by adding another option to the
$watch()
function.Yeah, I don’t mind if this ticket is closed with the solution suggested by posva.
Thank you.