2013-12-18 78 views
0

我試圖通過使用$腕錶,以紀念模型髒落實在我的模型的狀態屬性時,任何屬性的改變:

 $scope.$watch(
      function (scope) { 
       return scope.item; 
      }, 
      function (newItem, oldItem) { 
       if (newItem !== oldItem) { 
        newItem.setStateDirty(); 
       } 
      }); 

(有點明顯)的問題是,在任何狀態更改財產也觸發手錶。

如果沒有顯式比較所有屬性以確定是否只有狀態屬性已更改,是否可以以某種方式忽略狀態屬性的更改?

回答

0

我解決了這個問題,從不同的方向接近問題。我現在正在使用object.defineProperty()定義模型屬性,而不是爲我的模型使用簡單的JavaScript對象。這使我可以在特定屬性的setter中顯式設置髒標誌。

例如:

Object.defineProperty(this, "title", 
    { 
     set: function (value) { 
       _title = value; 
       this.dirty = true; 
      } 
    }); 
1

在您的$watch函數中,您可以返回一個新對象,其中包含item的所有屬性,但不希望$ watch的屬性除外。

$scope.$watch(
    function (scope) { 
     // return a new object in which the dirty property is always undefined 
     // and therefore will not trigger the watch 
     return angular.extend({}, scope.item, {dirty: undefined}); 
    }, 
    function (newItem, oldItem) { 
     if (newItem !== oldItem) { 
      newItem.setStateDirty(); 
     } 
    }); 
+0

有趣的建議,但我不知道,因爲性能原因,它可能是不明智的,這樣做在$手錶聽衆。 – user1843640

相關問題