0

first of all, I think the idea of object-oriented programming is just understandable if you are born later then 1980 ;). So please be kind, I'm much older.

My problem, I'm trying to get an Object into an Array, to make it easier to access it. I tried it with the below code, but when I try to access the Object, I get the error message, that it is undefined. Please give me a hint, where I have a error in my thinking.

var axles=[];

axles[0] = makeMySvg('holes.svg', 100, 100)

function makeMySvg(urlName, posx, posy)
{
    fabric.loadSVGFromURL(urlName,function(objects)
    {

            obj = new fabric.util.groupSVGElements(objects, {
              //left: versatzx-14, // 1/2 breite 28px hoehe 33px
              //top: versatzy+axpos1/10*factor,
              top: posx,
              left:posy,
              opacity: 1,
              scaleX: 1,
              scaleY: 1,
              objectCaching: true
            });

            canvas.add(obj);
            canvas.renderAll();
            return obj;
    });

}

axles[0].scaleX=10;
  • The `loadSVGFromURL` function is async - you can't use the objects and values it has created other than from the callback (or code called from it) – Alnitak Jan 15 '18 at 14:56
  • You cant return from a callback. That will return it somewhere into the js engine – Jonas Wilms Jan 15 '18 at 14:56
  • First issue: You have not specified what **makeMySvg** should return, therefore it will return **undefined*. Second issue: **loadSVGFromURL** is asynchronous: the callback where you define *obj* may be called sometime in the future. Third issue: you haven't defined *obj* before you assign a value to it, so it is a global variable. Use `var obj = (your code)` to define it. – some Jan 15 '18 at 15:00
  • You probably should add a *callback* to your **makeMySvg**-function, and in that callback you can add the result to axles `axles.push(obj)` and modify it. – some Jan 15 '18 at 15:03
  • @some personally I'd wrap it in a `Promise` instead. – Alnitak Jan 15 '18 at 15:04
  • @Alnitak Me too, but one concept at a time. I would put it in a class and use arrow-functions too, but since the poster is new to the language, I limited my comment to the concepts that he was already using. – some Jan 15 '18 at 15:07
  • Thanx for all the comments. A lot of things are now clearer to me, but I still have a bunch of questions. Sorry if they seem simple to the experienced javascript programmer, but I just starting to dig in. – Michael Roebbeling Jan 15 '18 at 19:38
  • I still have some questions, but I can not post my changed code and the problems here anymore, because it was tagged as a duplicate. Although the marked answer of the duplicate is very interesting, I can not get to a solution with it. – Michael Roebbeling Jan 15 '18 at 20:52

0 Answers0