1

I am new in Javascript and made a function structure like this:

var project = ... ; // it's dynamic

// first function
$('body').on('click', '.projectmonitoring', function () {
    SetMonitoring(project);
});

// second function
function SetMonitoring(project) {
    var tasks = ... ; // this variable produced inside Ajax

    // third function
    $('#save').click(function () {
        // do something using project and tasks variable
    });
}

Whenever I called the first function, SetMonitoring function was triggered of course. I called first function more than one (do a click twice or more). When I call the third function, what happens is the third function was executed much as the amount I called first function.

Maybe I am wrong in the structure. I hope has been explained well. Thanks in advance.

andrefadila
  • 647
  • 2
  • 9
  • 36

3 Answers3

0

Make a global var, set it in second function and then use it in third function.

var value_of_project;

// first function
$('body').on('click', '.projectmonitoring', function () {
    SetMonitoring(project);
});

// second function
function SetMonitoring(project) {
    //set value of project here
    value_of_project = "some value";
}

// third function
$('#save').click(function () {
    //do something using value_of_project 
});
Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133
0

Well, you can use: $('#save').off('click').click(function () { ... But a better solution would be restracturing your code. You do not need to pass project par to setmonitoring function if it's a global... But in any case attaching an event handler inside ivent handler is an anti pattern...

Beckafly
  • 411
  • 2
  • 5
0

To make sure your function is being called only once-

use one-

var project = ... ; // it's dynamic

// first function
$('body').one('click', '.projectmonitoring', function () {
    SetMonitoring(project);
});

// second function
function SetMonitoring(project) {
    var tasks = ... ; // this variable produced inside Ajax

    // third function
    $('#save').click(function () {
        // do something using project and tasks variable
    });
}
Manoz
  • 6,507
  • 13
  • 68
  • 114