0

How to run a function whenever values of its receiving arguments are changed

var data = [5, 6]
function add(first, second){ return first + second}
add(data[0], data[1])

Let data be a value received from server, whenever new data is recived function should rerun. I don't want to use setInterval() or setTimeout() because I want only function to be refreshed when different data is received

RegarBoy
  • 2,234
  • 15
  • 36
  • 1
    There must be an event of sort to track out the data change or callbacks on functions that work with the data. – MinusFour Oct 09 '15 at 11:05
  • Can you give any example? – RegarBoy Oct 09 '15 at 11:13
  • Ok so data is received from server? I guess you do that using ajax? so you could call the method with the new values in the onSuccess event. – bwright Oct 09 '15 at 11:16
  • If you use some framework, you get this feature. Like `watch() in AngularJS` or `subscribe() in Knockout JS`. But in both, variables are function and not a simple var variable, so it is easy to implement callback in them. – Rajesh Oct 09 '15 at 11:51
  • Also [Similar question](http://stackoverflow.com/questions/1759987/listening-for-variable-changes-in-javascript-or-jquery) – Rajesh Oct 09 '15 at 11:54

1 Answers1

3

if it's ajax then you should run function on success event for example

$.ajax({
    url: "example.php",
    type:"POST",
}).success(function(data) {
    add(data[0],data[1]);
});
  • But data has already been ran with ajax. I need to know a way to run the function whenever data is changed. Even if data is not getting received from server. – RegarBoy Oct 09 '15 at 14:59
  • success event triggers when ajax request finishes working with status code 200.it means that ajax request was successful, even if you don't receive any data from server. put your function in success event that will be triggered every time ajax request will be finished successfully. provide some code snippet if this was not helpful. – Irakli Chikvaidze Oct 09 '15 at 22:20