I am trying to write my objects in a separate js file to make my main HTML file easier to organise. When I use jquery or oCanvas (canvas library) syntax, it doesn't seem to recognise it and fails to execute. I want to be able to make object templates for my main to make clones from (using the clone() function in oCanvas).
Main HTML
<script language="javascript" type="text/javascript">
var canvas = oCanvas.create({
canvas: "#myCanvas",
background: "#CCCCCC"
});
helloworld();
</script>
External JS File
var rectangle = canvas.display.rectangle({
x: 77,
y: 77,
width: 200,
height: 100,
fill: "#0aa"
});
function helloworld(){
alert(rectangle.x);
};
When I call for the object rectangle
and alert it's x property it fails. Is this something to do with making the object global?
Because helloworld
is in a closure, you'll need to export it to an outer scope to use it somewhere else:
$(document).ready(function(){
var rectangle = canvas.display.rectangle({
x: 77,
y: 77,
width: 200,
height: 100,
fill: "#0aa"
});
function helloworld(){
alert(rectangle.x);
};
window.helloworld = helloworld; // make it global
});
However, the script you pasted calls the function immediately, and it won't be defined until after this runs. So you'd have to wait until the DOM is loaded before calling helloworld()
.
Remove $(document).ready(function(){
and });
since:
helloworld
is not a global so you can't reach it from your other script element and rectangle
won't be given a value until the DOM ready event has fired (which will be after your attempt to call helloworld
. After the edit to the question
This is your order of code execution:
rectangle
helloworld
which tries to read a value from rectangle
You have to create the canvas before you try to read data from it.
One of ways:
You should trigger your custom events:
$(document).ready(function(){
...
window.hello = function(name){alert('Hello, '+name+'!');}
// document.dispatchEvent(new CustomEvent('libLoaded', { name: 'hello' }));
document.dispatchEvent(new CustomEvent('libLoaded_hello', {}));
...
});
And wait it:
document.addEventListener('libLoaded_hello', function(e){
// console.log(e.name);
hello('World');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.