Suppose I work with a directive that dates a date as a unix timestamp using two-way binding, but also offers a calendar widget to change the selection.
The calendar widget works with a date object, and I cannot change the format of the input data, and I do not want to rework the calendar to support the unix timestamp. This is also just an example, and this is a general way of working with circular observers.
The area will look like this:
scope.selectedUnixTimestamp;
scope.selectedDate;
scope.$watch('selectedUnixTimestamp', function(newV, oldV) {
$scope.selectedDate = new Date(newV*1000);
});
scope.$watch('selectedDate', function(newV, oldV) {
$scope.selectedUnixTimestamp = Math.floor(newV.getTime()/1000 + 0.000001);
});
My question is: what should I do to avoid extra calls $ watch callbacks? Obviously, if I select a new date, the stream will look like this:
- Watcher # 2 is called - it changes the selected UnixTimestamp
- Called by Watcher # 1 - it modifies selectedDate
- Watcher # 2 ( ) - UnixTimestamp
, . ?
, - :
scope.selectedUnixTimestamp;
scope.selectedDate;
var surpressWatch1 = false;
var surpressWatch2 = false;
scope.$watch('selectedUnixTimestamp', function(newV, oldV) {
if(surpressWatch1) { surpressWatch1 = false; return; }
$scope.selectedDate = new Date(newV*1000);
surpressWatch2 = true;
});
scope.$watch('selectedDate', function(newV, oldV) {
if(surpressWatch2) { surpressWatch2 = false; return; }
$scope.selectedUnixTimestamp = Math.floor(newV.getTime()/1000 + 0.000001);
surpressWatch1 = true;
});
.
- :
scope.selectedUnixTimestamp;
scope.selectedDate;
scope.$watch('selectedUnixTimestamp', function(newV, oldV) {
if(newV*1000 === scope.selectedDate.getTime()) { return; }
$scope.selectedDate = new Date(newV*1000);
});
scope.$watch('selectedDate', function(newV, oldV) {
if(scope.selectedUnixTimestamp*1000 === newV.getTime()) { return; }
$scope.selectedUnixTimestamp = Math.floor(newV.getTime()/1000 + 0.000001);
});
, , * 1000
:
scope.$watch('selectedDate.getTime()', function(newV, oldV) {