1

I work with javascript. Let's suppose I have the following function in my app:

function verify(cats) {
  if ( cats > 20 ) {
    // do something
  }
}

Supposing i have a button to add cats, I may use that function after every cat adding. However, i don't like this method.

I want that this function be in the background and is executed automatically when the condition states true

Is there some way to do so ?

Léo
  • 41
  • 4

2 Answers2

5

Use a setter, that runs on every assignment. Before:

var obj = {};
obj.cats = 10;
obj.cats += 30;
verify(obj.cats); // we don't want to call this each time.

After:

var obj = {
    _cats : 0, // private
    get cats() { return this._cats; },
    set cats(num) {
        verify(num); // any verification here
        this._cats = num;
    }
};

Later, you can do:

obj.cats += 10; // will run verification
obj.cats = 15; // same

Alternatively, you can use a proxy, but those aren't really widely supported by JS engines yet.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • Thumbs up for setters/getters, but small nitpick would be that _cats is never private. – rob Sep 23 '15 at 14:33
  • 1
    @RobertOliveira privacy here is about communication and not security in this case. The "we're all consenting adults, if it has a `_` in front of it don't touch it" thing has been working out pretty well for us. Real privacy can be accomplished with a WeakMap or a closure. Thanks for pointing that out. – Benjamin Gruenbaum Sep 23 '15 at 14:46
  • Nice ecample. Yet it still run on every assignment which the op didn't like, but there is really no other way... So IMO the simplest solution is the original function – MrE Sep 23 '15 at 15:12
  • @MrE I'm pretty sure OP doesn't like _calling_ it every time the value changes as in _having to remember to call verify each time_ (which is error prone). Not the overhead of the actual call. – Benjamin Gruenbaum Sep 23 '15 at 15:17
-1

How about setInterval()

$(function() {
    setInterval(
        function verify(cats) {
          if ( cats > 20 ) {
            // do something
          }
        }

    , 10);
})
g2000
  • 480
  • 3
  • 8
  • of course it's undefined.. it's gotta set somewhere else... what he put is just a code extract ... – g2000 Sep 23 '15 at 14:19
  • no, as you create a closure with a variable named `cats` it can't be set somewhere else. `setInterval` will call this function without any parameter so `cats` will always be undefined – Hacketo Sep 23 '15 at 14:21
  • this is a closure concept.. if u put that on top.. it should work.. http://jsfiddle.net/g2000/m6t3u58k/2/ – g2000 Sep 23 '15 at 14:30
  • 1
    with this fiddle you have the perfect example of variable shadowing (fiddle does not work but if jquery was included and if the console.log was in the condition, it would never log something) – Hacketo Sep 23 '15 at 14:33