简体   繁体   中英

How can I use libraries in external js files?

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:

  • By defining it inside another function, 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:

  1. Call a function on the canvas and assign the value to rectangle
  2. Create the canvas
  3. Call 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM