0

I am trying to create a closure in my for loop, how ever, it keeps returning a function instead of a string.

$(function() {
    var addID = function(id) {
        var temp = id;
        return function() {
            return "http://localhost:3000/board/raptrex/" + temp;
        }
    };

    $.get("http://localhost:3000/board/raptrex", function( data ) {
        console.log(data);
        var $deleteUL = $('#delete');
        for (var i = 0; i < data.length; i++) {
            var url = addID(data[i]._id);

            console.log(url);

            var $item = $('<li></li>').text(data[i].name).click(function() {
                $.ajax({
                  type: "DELETE",
                  url: url
                })
                  .done(function( msg ) {
                    alert( "Deleted: " + msg );
                  });
            });
            $deleteUL.append($item);
        }
    }); 
});

This returns http://localhost:3000/function%20()%20{%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20return%20%22http://localhost:3000/board/raptrex/%22%20+%20temp;%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20} when I click on my li element

1 Answer 1

2

You're returning a function instead of a string with addID. Try the following:

var addID = function(id) {
    var temp = id;
    return "http://localhost:3000/board/raptrex/" + temp;
};
Sign up to request clarification or add additional context in comments.

4 Comments

This is correct. Side question, when I click listener is fired, the url is always the last one, how would I fix that?
Right, I don't see that! Put the var url = addID(data[i]._id); inside the listener function and before the $.ajax call.
I cant as data[i]._id becomes undefined when you click on it
Right. I don't know how is your DOM but you can try to put the var url = addID(data[$(this).index()]._id); inside the listener. If all your <li></li> are in the same level and you don't have more <li> items in your document, this should work for you.

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.