1

I'm importing an SVG file into my paper JS script with importSVG and a callback function like below. However, I'd like to use the item variable that I imported outside of the scope of the callback function. I've tried using closures by encapsulating the load_svg function in brackets. However, I couldn't get that to work. How do I get around this?

$(document).ready(function() {
    paper.setup("myCanvas");
    with (paper) {

        var load_svg = function(item) {
            console.log("imported SVG!");
        };

        var url = "http://localhost:3000/13.svg";
        project.importSVG(url, {
            expandShapes: true,
            onLoad: load_svg()
        });
    }
});

Thanks!

Fraction
  • 11,668
  • 5
  • 28
  • 48
SumakuTension
  • 542
  • 1
  • 9
  • 26
  • 2
    It's not an issue of scope. It's an issue of time. You can prove this to yourself by saving `item` to a global variable then in a after calling `importSVG` do this `setTimeout(function(){ console.log(global_item_var) } , 2000)` <- access the global var after 2 seconds – slebetman Jul 11 '19 at 10:14
  • 1
    Because of this there is no solution to what you think you want to do but there is a solution for javascript programmers. The solution is the callback function. Anything you want to do to `item` you do inside the callback function. You are free to call any other function inside your callback function. So the real solution is you just have to learn how to code in this way – slebetman Jul 11 '19 at 10:15
  • what is your item and where has it come from? where is it in relation to this .ready callback? – Will Jenkins Jul 11 '19 at 10:18
  • `onLoad: load_svg` without the parentheses – you're calling the function immediately instead of passing it as a callback. – JJJ Jul 11 '19 at 10:50
  • As stated in the above comments, your main problem is understanding the asynchronous nature of JavaScript. You have to first load your SVG, then do something with it. Here is a [fiddle](https://jsfiddle.net/dwtyx3m8/) demonstrating one possible way to do this. – sasensi Jul 11 '19 at 12:00

0 Answers0