Search code examples
javascriptraphaelsnap.svgsvg-animate

Why when I add function into Snap.load(...loading SVG... my method...) I cannot then call this method, which is inside to Snap.Load()?


Why when I add function into Snap.load(...loading SVG... my method...) I cannot then call this method, which is inside to Snap.Load()?

function myComponent() {
    var paper = Snap("#svg3");

    Snap.load("svg/thermometer_o.svg", function (f) {
        paper.append(f);
        paper.selectAll("#empty").attr({fill: "#f00"});

       myMethod = function(perc){
            var v= 350 * ((perc) / 100);
            var py = (557 - v);
           animate = function(){   
          paper.selectAll("#empty").animate({height: v, y: py, x: "340"}, 3000);};
    };      


    });
}


function onPageLoad() {
    componentThermometer().myMethod(40);

} 

Solution

  • There's a few problems, maybe some are related to just pasting some bits onto SO though, but I'll mention them in case.

    What or where is componentThermometer() ? I don't see it defined anywhere.

    If that somehow calls myComponent, you need to think about your order of events. Snap.load is asynchronous, so could take any amount of time.

    So you call componentThermometer.MyMethod() when the page has finished loading.

    If we know think about the logic of that myComponent...myMethod isn't available until the Snap.load has finished. So I'm not quite sure how that method is ever available, unless there is something going on in a missing bit of code somewhere.

    What I imagine you want to do, is put myMethod outside of the Snap.load handler (I can't see any reason currently for it to be there). And you may want to only call myMethod after the Snap.load has finished (as opposed to it currently being defined after the load).

    It would help if you can get a test example up just with the basics on a jsfiddle to help further though.

    From the codepen, here is how I would do it...

    var paper = Snap("#svg3");
    
    function componentThermometer( perc ) {         
        Snap.load("https://raw.githubusercontent.com/chovancova/project/master/public_html/teplomer_1/svg/thermometer_o.svg", function(f){
            paper.append(f);
            paper.selectAll("#empty").attr({fill:"#f00"});
    
            animateThermometer( perc );       
      });
    };   
    
    
    function animateThermometer( perc ) {  
            var vyska =  350*( perc / 100);
            var py = 557-vyska  ;
            paper.selectAll("#empty").animate({height: vyska, y:py, x:"342.882"}, 800);
    };
    
    componentThermometer(50);