[英]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. 我试图将我的对象写在一个单独的js文件中,以使我的主要HTML文件更易于组织。 When I use jquery or oCanvas (canvas library) syntax, it doesn't seem to recognise it and fails to execute.
当我使用jquery或oCanvas(画布库)语法时,它似乎无法识别并且无法执行。 I want to be able to make object templates for my main to make clones from (using the clone() function in oCanvas).
我希望能够为我的主体创建对象模板,以从中创建克隆(使用oCanvas中的clone()函数)。
Main HTML 主HTML
<script language="javascript" type="text/javascript">
var canvas = oCanvas.create({
canvas: "#myCanvas",
background: "#CCCCCC"
});
helloworld();
</script>
External JS File 外部JS文件
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. 当我调用对象
rectangle
并警告它的x属性时,它会失败。 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: 由于
helloworld
位于封闭中,因此您需要将其导出到外部作用域以在其他地方使用它:
$(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()
. 因此,您必须等到DOM加载后才能调用
helloworld()
。
Remove $(document).ready(function(){
and });
删除
$(document).ready(function(){
和});
since: 以来:
helloworld
is not a global so you can't reach it from your other script element and helloworld
不是全局的,因此您无法从其他脚本元素访问它, 并且 rectangle
won't be given a value until the DOM ready event has fired (which will be after your attempt to call helloworld
. helloworld
之后), rectangle
才会被赋值。 After the edit to the question 编辑问题后
This is your order of code execution: 这是您的代码执行顺序:
rectangle
rectangle
helloworld
which tries to read a value from rectangle
helloworld
尝试从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');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.