views:

483

answers:

4

Is there a way to call a javascript function if a javascript variable changes values using jQuery?

Something to the extend of -

var test = 1;
test = 2; // calls a javascript function
test = 3; // calls a javascript function

This way I wouldn't have to add an onchange event to so many different functions.

+1  A: 

No, there is not, just polling with setInterval or setTimeout or callbacks. Events only apply to DOM. I'd suggest that you try to go with callbacks and do things like this:

function foo(data, callback)
{
    // do things with data
    callback(data);
}

function bar(data)
{
    console.log('callback can has', data);
}

foo('baz', bar);

It's a rough example, but should give you the idea.

Reinis I.
+5  A: 

(Something seems a bit carelessly planned in your code if you need functionality like that)

The easiest way to add that feature is to create a function for updating your variable, that also calls whatever other function you want to.

Instead of:

var test = 1;
test = 2; // calls a javascript function
test = 3; // calls a javascript function

You do:

var test = 1;

function set_test(newval) {
  test = newval;
  my_callback(); // this is whatever you wanted to call onChange
}

set_test(2);
set_test(3);
Joel L
+1 After reading the others, this is clearly the best answer.
Evildonald
+1 for "Something seems a bit carelessly planned in your code if you need functionality like that". Quite true.
Daniel Pryden
A: 
The below function will poll for changes in the test variable every 5 seconds:

// initialize test variable globally
var test = 1;

// global variable to store the previous value of test
// which is updated every 5 seconds
var tmp = test;

setInterval("pollForVariableChange()", 5000);

function pollForVariableChange() {
    if (tmp != test) {
        alert('Value of test has changed to ' + test);
    }
    tmp = test;
}
cballou
+1  A: 

One option is to wrap your data into a heavier object.

var Watching = function(){
    var a;

    this.getA(){
        return a;
    };

    this.setA(value){
        a = value;
        this.trigger('watch');
    };

    his.watchA(callback){
        this.bind('watch', callback);
    };
};

var obj = new Watching();
obj.watchA(function(){ alert('changed'); });
obj.setA(2);
Matt