2

lets say I have a variable as follows:

var i=0;

If any one changes the value of i, I need to run some function like as follows

function event_iChanged(){
   alert("I Changed");
}

How can I do it in JQuery or Javascript ?

user3191903
  • 237
  • 2
  • 6
  • 14

3 Answers3

-1

You can add a listener to your document

$(document).on("myEvent", event_iChanged);

And whenever you change the value of your variable, just call

$.event.trigger({
    type: "myEvent",
    message: "i changed!",
    time: new Date()
});
Kalzem
  • 7,320
  • 6
  • 54
  • 79
-1

Solution - Mutator methods

Maybe you should consider about using a mutator method (getter/setter) like this:

function SetValue(reference, newvalue) {
  console.log("Old value: " + reference);
  console.log("New value: " + newvalue);
  reference = newvalue;
}

Mutator methods in non-object-oriented environments:

A reference to the variable to be modified is passed to the mutator, along with the new value. In this scenario, the compiler cannot restrict code from bypassing the mutator method and changing the variable directly. The onus falls to the developers to ensure the variable is only modified through the mutator method and not modified directly.

This means you should use it like this.

var i = 0;
SetValue(i, 10);
ˈvɔlə
  • 9,204
  • 10
  • 63
  • 89
-2

A solution could be to use Observer Pattern, take a look here.

Otherwise, instead of creating wacther or use different plugin, you can consider to create a function that set value to x and, in add, call another function:

instead of:

x = 3;

you will have:

set(x,3);

where:

var set = function(v, value) {
    v = value;
    callback(v);
}

DEMO here.

Community
  • 1
  • 1
Luca Davanzo
  • 21,000
  • 15
  • 120
  • 146