0

I have a JavaScript function that runs every time one of the many links is clicked. The functions first checks what the id of the link clicked is, then it runs an if stement. depending on the id of the link, different variables are defined.

All this works, but the problem is that some links define one variable while other links define another, I need to keep the variables defined in previous executions of the function defined for other executions of the function.

An example follows:

$(document).ready(function()
{
  $(".sidebar a").click(function(event) {
    event.preventDefault()
    var targetID = $(this).attr("data-target")
    $("#" + targetID).attr("src", $(this).attr("href"))
    var element = $(this).attr("class")
    if (element == "submit") {
      var submit = $(this).attr("user")
      alert("1")
    } else if (element == "view") {
      var view = $(this).attr("user")
      alert("2")
    }
  })
  window.history.replaceState({}, 'logs', '/file/path?submit=' + submit + '&' + 'view=' + view)
})

Thanks

3
  • 1
    You're missing a bunch of semicolons there... Commented Feb 8, 2013 at 1:22
  • Im sure my code is sloppy, but I know what I currently have works, all I need is to get the variables to go from inside to outside of the function Commented Feb 8, 2013 at 1:23
  • I'm not saying it shouldn't just that it looks confusing, either use semicolons or not, but mixing like that is confusing, same with the double and single quotes. Trying to solve problems with sloppy code is always a bad idea, because when it comes time to refactor it'll be a huge mess already. Commented Feb 8, 2013 at 1:24

4 Answers 4

3

You can use an outer function which does nothing but declare some variables and return an inner function. The inner function can access the variables from the outer scope which stay the same for every call of the function.

Example

var next = (function() {
    var value = 0;
    function next() {
        return value++;
    }
}());

console.log(next());
console.log(next());
console.log(next());

Live demo

http://jsfiddle.net/bikeshedder/UZKtE/

Sign up to request clarification or add additional context in comments.

Comments

1

Define the variables in an outer scope:

$(document).ready(function () {
    var submit;
    var view;

    $(".sidebar a").click(function (event) {
        event.preventDefault();
        var targetID = $(this).attr("data-target");
        $("#" + targetID).attr("src", $(this).attr("href"));
        var element = $(this).attr("class")
        if (element == 'submit') {
            submit = $(this).attr("user")
            alert("1")
        } else if (element == 'view') {
            view = $(this).attr("user")
            alert("2")
        }
    });
});

4 Comments

I have already tried that, it sounded like a good idea, but unfortunately it does the same thing as before.
@zggz12 What thing does it do?
It does the exact same thing as defining the variables inside the function. It always puts the variable that isn't being defined in that run of the function is set to undefined
@zggz12 You have to remove var from the assignments to submit, and view in the click handler. Did you do that? (See my code above)
0

Create var submit and view outside of the function so it has a global scope.

4 Comments

Bad advice. The use of global variables should be minimized.
No, it is good advice, as it is the simplest and most obvious approach. Creating a new scope just to avoid global variables merely obfuscates it. But be sure the variable names are clear and unique. In a large, multi-package project, such names should begin with the package name.
haha! well my point is that in order to keep these variables available they need to be outside the method scope...
Outside the click handler scope, yes. But there is of course not need to make them global, as one can declare them in the scope of the ready handler, or even introduce an additional scope.
0

You can store arbitrary data on a matched element with JQuery's .data() function.

Example:

$(this).data("submit", $(this).attr("user")); // set a value

var submit = $(this).data("submit"); // retrieve a value

This places the data in the context of JQuery's knowledge of the element, so it can be shared between function calls and even between different events.

1 Comment

Is there anything that I would need to do to initializing this?...I tried to put the "$(this).data("submit", $(this).attr("user"))" inside the if statement, and the "var submit = $(this).data("submit")" before the part that works with the variables, it didn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.