3

I set up an anchor tag using javascript so that that onclick, I call a function showSavingsEasterEgg and pass it a value. The problem I am getting is that I'm not referencing my function correctly:

ReferenceError: showSavingsEasterEgg is not defined

I've tried moving the showSavingsEasterEgg function into the showData function to see if it solved the scoping problem, but it didn't.

Any tips

define(["jquery", "go/util", "underscore", "jqueryui/slider"], function ($, util,_) {

  function showData(data) {
    $('#item').append('<a class="savings_link" href="#" onclick=\'showSavingsEasterEgg('+data[key]['saving']+')\'> Savings');
  }

  function showSavingsEasterEgg(data){
    console.log("SUccess");
    console.log(data);
  }

});
1
  • btw ReferenceError: define is not defined Commented Nov 10, 2012 at 18:57

4 Answers 4

8

Put the definition of showSavingsEasterEgg directly in the global scope.

Here, it can't be found.

You can do this :

window.showSavingsEasterEgg = function (data){
    console.log("SUccess");
    console.log(data);
};
define(["jquery", "go/util", "underscore", "jqueryui/slider"], function ($, util,_) {
  function showData(data) {
    $('#item').append('<a class="savings_link" href="#" onclick=\'showSavingsEasterEgg('+data[key]['saving']+')\'> Savings');
  }
});
Sign up to request clarification or add additional context in comments.

2 Comments

do you know what is define() here ?
@eicto no, but that's not the problem : "showSavingsEasterEgg is not defined".
2

Wondering why nobody suggested the most obvious, convenient and "best practice" way so far. You shouldn't use inline event handling at all, do it unobtrusive.

$('#item').append($('<a>', {
    'class':    'savings_link',
    href:       '#',
    click:      function(e) {
        console.log("SUccess");
        console.log(data);
    }
}});

1 Comment

I wanted to use onClick because I have several anchor tags with the same ID and if I clicked on one with an event listener, my function gets called several times.
1

Make showSavingsEasterEgg global. you can call only globally accessible objects/references from html code.

 window.showSavingsEasterEgg = function(data){
    console.log("SUccess");
    console.log(data);
  }

Comments

0

You should know and understand what is the definition of "scope" in any programming languages. Please move the function named "showSavingsEasterEgg" out side of the parent function and it will work like a charm. It's because you defined it as a private member of the parent function.

Cheers

Comments

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.