0

I have a block of code in $(function() { function parseData(){...} )};

I also have a function declared outside of the ready block. This is outside since I hook it up in codebehind ie ddlCategories.Attributes.Add("onchange", "getDataFields()");

From the getDataFields function, I need to call parseData but it does not seem to find it.

How do I access my parseData() which is in my ready block, from outside of the ready block?

(sorry if some of terminology is off - I am now to JS)

Jeff
  • 2,061
  • 4
  • 27
  • 45

4 Answers4

1

Just define it outside your ready block. It's currently inaccessible due to the scope of the function.

Definitions can always safely go outside $(function() { ... }) blocks because nothing is executed.

$(function() { ... });

function parseData() { ... }

However, you seem to have a syntax error: )}; should be });.

pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • The syntax was because I was typing off the cuff. – Jeff Jul 18 '11 at 14:59
  • @Jeff: If you would like to access functions everywhere, you should expose them directly instead of inside `$(...)` blocks. Otherwise, those functions would not be accessible outside the `$(...)`. This behaviour is called 'scope'. – pimvdb Jul 18 '11 at 15:02
1

Any reason parseData() has to be in the ready block? Why not just make it a top level function:

<script type="text/javascript">

function parseData() { ... }

$(document).ready( function() {
   ddl.Categories.....
}
<script>
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • Well, then I will have the same issue elsewhere, since other things call parseData(). – Jeff Jul 18 '11 at 15:01
  • Yes, but what's parseData doing? Unless it's doing dom manipulations, then there's no reason it can't be a top level functionality, which makes it available to all your scripts, regardless of where/when they execute. – Marc B Jul 18 '11 at 15:04
  • I just tried this. I have a bunch of variables that are defined inside the ready block so that makes it difficult. Is there no way to call into a function in the ready block? – Jeff Jul 18 '11 at 15:08
  • global variables aren't a good idea. but if you need them, then put their original definition outside the block, then set their values in the ready block. – Marc B Jul 18 '11 at 15:16
1

Declare your parseData function outside of the self-executing $(function(){}); block.

var parseData = function () { ... };

$(function() { ... });

If there are things you need to reference inside the self-executing function, then declare the function globally but define it inside the self-executing function:

var parseData;

$(function() { parseData = function () { ... }; });

As an aside, declaring functions or variables globally is a bad idea.

jbabey
  • 45,965
  • 12
  • 71
  • 94
0

You should declare the function outside the $(function() { ... }) callback.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964