Reputation: 6301
I have a page on which I'm using JQuery Mobile. I am having difficulty understanding when exactly my variables are visible. I thought that the following were loaded into the same memory space. But I get an error. Before I explain the error let me show the code:
Page.html
<html>
<head>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id="myPage" data-role="page">
<div data-role="header">
<h1>My App</h1>
</div>
<div data-role="content">
<div class="ui-grid-a">
<div class="ui-block-a"><input type="button" value="First" onclick="return button1_Click();" /></div>
<div class="ui-block-b"><input type="button" value="Second" onclick="return button2_Click();" /></div>
</div>
</div>
<script type="text/javascript">
var currentIndex = 0;
function button1_Click() {
alert(myCollection.length);
}
function button2_Click() {
}
</script>
</div>
</body>
</html>
App.js
$("#myPage").live("pagecreate", function () {
});
$("#myPage").live("pagebeforeshow", function () {
});
$("#myPage").live("pageshow", function () {
var myCollection = loadCollection();
function loadCollection() {
// do stuff
}
});
When I click the "First" button, my event handler is called. However, I receive the following error:
ReferenceError: myCollection is not defined
My question is how can I share variables between these two files? I'm also concerned about name collisions which is why I was hope to share the memory space in the manner I attempted below. What am I doing wrong?
Thank you.
Upvotes: 1
Views: 384
Reputation: 707326
myCollection
is defined within the scope of a callback function and thus only exists within that callback function. It is not available outside that scope. If you want it available globally, you have to define it as a global variable, outside of a function scope.
Your code in app.js also should be surrounded with $(document).ready()
because you're trying to reference the DOM before it exists.
Upvotes: 1