1

I am generating links from json files on the client side.

loadSubjects = function() {
  return importData("themen", function() {
    var i, _i, _ref, _results;
    _results = [];
    for (i = _i = 0, _ref = data.themen.themen.length - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) {
      $("#subjectBtns").append('<a href="javascript:generateSubjectOverview("' + data["themen"]["themen"][i]["dateiName"] + '");" class="btn btn-mghg">' + data["themen"]["themen"][i]["name"] + '</a>');
      console.log('appending: ' + '<a href="javascript:generateSubjectOverview("' + data["themen"]["themen"][i]["dateiName"] + '");" class="btn btn-mghg">' + data["themen"]["themen"][i]["name"] + '</a>');
      _results.push(false);
    }
    return _results;
  });
};

I also tired onlick instead of href, but that also didnt work. I am getting the error: Uncaught SyntaxError: Unexpected end of input

The javascript code looks somewhat messy, but that is, because it´s generated by coffeescript.

the function importData is just a short hand for $.getJSON with the path and the callback

6
  • You can't return results from an AJAX callback. The callback function runs asynchronously when the server responds. Commented Jul 27, 2014 at 11:53
  • @Barmar: I think the return there is to return the jqXHR object (or possibly another promise of some kind). Ben is passing in a callback. (Hmmmm... But then, why return _results; at the end of the callback? Maybe importData does something with that.) Commented Jul 27, 2014 at 11:59
  • he said importData is just shorthand for $.getJSON. Unless it's wrapping the callback in another function that does something with the return value, it won't be used. Commented Jul 27, 2014 at 12:02
  • @Barmar: Sometimes people say "shorthand" even when doing a small thing differently. Ben's the only one who can really answer, but is clearly aware of the need for callbacks. Commented Jul 27, 2014 at 12:06
  • 1
    return _results; is just because i am writing in coffeesctipt. it always return the last thing in a codeblock Commented Jul 27, 2014 at 17:13

2 Answers 2

2

To call a function when the link is clicked, use the click event rather than trying to generate JavaScript source with the arguments in it to put on the href:

$("#subjectBtns").append(
    $('<a href="javascript:;" class="btn btn-mghg"></a>')
        .click(generateSubjectOverview.bind(null, data["themen"]["themen"][i]["dateiName"]))
        .append(data["themen"]["themen"][i]["name"])
);

This bit:

generateSubjectOverview.bind(null, data["themen"]["themen"][i]["dateiName"])

...looks up the value from the data object and binds that value to generateSubjectOverview, setting up a click handler to call the resulting bound function. The result is the same, but you don't make an unnecessary round-trip through JavaScript source code, so this works not just for strings and numbers, but any kind of argument you may want to pass.


Note: Function#bind is an ES5 feature. If you still need to support really old browsers (IE8, for instance), it can be shimmed. Search for "Function bind shim" to find options.

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

2 Comments

what does the null in .click(generateSubjectOverview.bind(null, data["themen"]["themen"][i]["dateiName"])) do?
@Ben: The first argument to Function#bind determines what this will be when the original function is called: In loose mode, if it's undefined or null, the original function is called with this equal to the global object (window, on browsers). (In strict mode, the value is used as-is.) Any other arguments you give bind are passed on to the called function. So in loose mode, if you do var bound = foo.bind(null, 1, 2); and then you do bound('a', 'b', 'c');, foo gets called with this being the global object and the arguments 1, 2, 'a', 'b', 'c'.
1

You have a problem with ' and ". change this

 $("#subjectBtns").append('<a href="javascript:generateSubjectOverview("' + data["themen"]["themen"][i]["dateiName"] + '");" class="btn btn-mghg">' + data["themen"]["themen"][i]["name"] + '</a>');

to this

 $("#subjectBtns").append('<a href="javascript:generateSubjectOverview(\"' + data["themen"]["themen"][i]["dateiName"] + '\");" class="btn btn-mghg">' + data["themen"]["themen"][i]["name"] + '</a>');

2 Comments

what do those slashes do?
the slashes allow to show the char " inside a string which is between " String "

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.