0

I'm writing javascript which fetches the users GPS coordinates (once) then calculates the distance between him/her and the a list of restaurants I'm displaying on the page.

$(document).bind("DOMNodeInserted", function(e) {

    if($('#user-gps').length) {

        $('.restaurant').each(function(index, value) {
            var lat = $(value).find('.latitude').attr('data-src');
            var long = $(value).find('.longitude').attr('data-src');

            var distance = geolocator.calcDistance({
                from: {
                    latitude: $('#user-gps').attr('lat'),
                    longitude: $('#user-gps').attr('long')
                },
                to: {
                    latitude: lat,
                    longitude: long
                },
                    formula: geolocator.DistanceFormula.HAVERSINE,
                    unitSystem: geolocator.UnitSystem.METRIC
            });

            var string = Math.round(distance * 10) / 10 + "km";
            var restaurantTitle = '#restaurant-' + index + ' .restaurant-title';
            //$(restaurantTitle).append(string);
            //
            console.log($(restaurantTitle));

            //console.log($(value).find('.restaurant-title').text() + " - " + Math.round(distance, -1) + "km");
            $(restaurantTitle).append('<span>' + string + '</span>');
        });
    }

});

I'm looping through each restaurant and calculating the distance, after which I format the string to display a value like 3.2km. I then want to append this in the DOM.

$(restaurantTitle).append('<span>' + string + '</span>');

As soon as I try this I get a Maximum Call Stack Exceeded error in the console.

I have tried several ways to make sure I'm only selecting the element I'm currently iterating over. I have even given each .restaurant a unique ID. The selector works perfectly fine but I cannot append or in any way add the string without getting the error.

Any help is much appreciated.

1
  • 1
    Please post a runnable minimal reproducible example to the question using Stack Snippets (the <> toolbar button). That will let people see the problem and help you solve it, while ensuring that all necessary content is here on-site. Commented Oct 1, 2016 at 14:25

1 Answer 1

5

You've bound this to the DOMNodeInserted event on the document level, and when you insert the span you're inserting a DOM Node, triggering that event, which in turn inserts a span, that triggers the DOMNodeInserted event, that inserts a span that triggers ... and on it goes, until the stack is full.

You have to rethink your logic, and find some other event or way to do what you want

Sign up to request clarification or add additional context in comments.

5 Comments

I agree that that's the problem, but I'm a little confused at how that would cause a call stack problem. Shouldn't the events caused by those .append() calls in the initial handler happen in new event loops?
@Pointy - I don't think it does, it seems like the message queue is filled up as the elements are inserted, and it doesn't have time to tick over before firing the next etc, and as it's single threaded it fills up the stack without being able to clear items of it (or something like that) ?
This always happen when you trigger events inside event handlers -> jsfiddle.net/yoctn5ue and jsfiddle.net/yoctn5ue/1
Yes that could be it I guess; it's certainly piling up something, somewhere.
Thanks. I changed the first if statement to if(e.target.id == 'user-gps') to ensure that the code only fires when this dom element gets added, which only happens once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.