jQuery trigger on variable change

2019-01-28 05:57发布

I have a setup where i load many modules as required, each module has a specific load needs when a specific variable is changed. I need something like jquery trigger but that runs when a variable change, something like this:

var x = 0; // no triggers

// something happens

x = 1; // will trigger a function
x = 2; // will trigger the same function

Thanks.

2条回答
时光不老,我们不散
2楼-- · 2019-01-28 06:17

Perhaps you could create an object that contains a set_x method to change the value of the variable. In addition to changing the variable, this method could call any associated triggers.

Then instead of setting x directly, you would use this new method:

my_obj.set_x( 2 ); // Will trigger a function
查看更多
混吃等死
3楼-- · 2019-01-28 06:29

How about this?

var x = {
    value: 10
}

var set = function(obj, new_value) {
    obj.value = new_value;
    /* call whatever your heart desires here */
}

So you can do:

set(x, 2);
// now x.value = 2
查看更多
登录 后发表回答