2014-10-26 56 views
0

​​聰明的方法來繞過視野的去抖動?

基本上,我希望我的範圍。$手錶兌現debounce,但希望一個單獨的觀察者爲我的觀點沒有反彈。我可以使用任何非骯髒的技術?

<my-slider></my-slider> 

<script type="text/coffeescript"> 
angular.module('myApp', []) 
.directive 'mySlider', -> 
    link = (scope) -> 
    scope.sliderValue = 0 
    scope.$watch 'sliderValue', (value) -> 
     console.log 'Slider Value: ' + value 

    link: link, 
    restrict: 'E', 
    template: 
    'Value: {{sliderValue}}<br>' + 
    '<input type="range" step="1" min="0" max="10" ' + 
    'ng-model="sliderValue" ng-model-options="{ debounce: 1000 }" />' 

angular.bootstrap document, ['myApp'] 
</script> 

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.js"></script> 
+0

「獨立觀察家對我的看法,而不去抖」?在你的代碼中,你正在使用'ng-model-options'來爲你的模型設置1秒的「debounce」。現在你想爲那個沒有「debounce」的模型有一個'watch watch'?你知道這聽起來有多矛盾嗎?也許你可以使用一箇中間的'模型',這首先會挫敗'debounce'的目的。例如:從您的 Josep 2014-10-26 17:03:44

+0

@Joseph讓心理安撫使用者。沒有人喜歡切換窗體控件並獲得延遲的反饋,但後端處理不需要執行滑塊的每個節拍。這是如何相互矛盾的? – CodeShaman 2014-10-26 18:43:12

+0

「後端處理不需要執行滑塊的每個記號」<---「debounce」選項與後端無關。如果您設置1秒的「debounce」,則在用戶更新「輸入」的時間過去1秒後,模型將不會更新。換句話說:如果您的模型設置爲1秒的「debounce」,則在一秒鐘之後您將無法獲知有關模型的新值,因爲模型的值將不會更新,直到秒後。對於你所說的話,我覺得你想要的是一個自定義的'debounce'函數。 – Josep 2014-10-26 19:56:30

回答

1

我認爲,你想要的是這樣的:

angular.module("myApp", []).directive "mySlider", ($timeout) -> 
    link = undefined 
    link = (scope) -> 
    debouncePromise = undefined 
    scope.sliderValue = 0 
    scope.$watch "sliderValue", (value, oldVal) -> 
     return unless oldVal 
     $timeout.cancel debouncePromise if debouncePromise 
     debouncePromise = $timeout(-> 

     #your call to the server here! 
     console.log value 
     return 
     , 1000) 
     return 

    return 

    link: link 
    restrict: "E" 
    template: "Value: {{sliderValue}}<br>" + "<input type=\"range\" step=\"1\" min=\"0\" max=\"10\" " + "ng-model=\"sliderValue\" />" 

Example