$observe multiple attributes at the same time and fire callback only once

前端 未结 5 1717
灰色年华
灰色年华 2021-02-19 20:38

I wonder is it possible to execute some callback only once after evaluation all (or only some) attributes of directive (without isolated scope). Attributes are really great to p

5条回答
  •  忘了有多久
    2021-02-19 21:15

    I resolved the exact same problem that I had using another approach, though I was looking for different ideas. While cmw's suggestions is working, I compared its performance against mine, and saw that the $watch method is called far too many times, so I decided to keep things the way I had implemented.

    I added $observe calls for both variables I wanted to track and bound them to a debounce call. Since they both are modified with very little time difference, both $observe methods trigger the same function call, which gets executed after a short delay:

    var debounceUpdate = _.debounce(function () {
        setMinAndMaxValue(attrs['minFieldName'], attrs['maxFieldName']);
    }, 100);
    
    attrs.$observe('minFieldName', function () {
        debounceUpdate();
    });
    
    attrs.$observe('maxFieldName', function () {
        debounceUpdate();
    });
    

提交回复
热议问题