Very basic javascript function call

2019-07-19 14:43发布

问题:

I have been doing leaflet API since 2 days. I have been stuck in a function call which gives me unexpected behaviour. the code is as follows

var it=0;

var map = L.map('map1', {
    center:[51.505,-0.09],
    zoom: 2,
});

L.tileLayer('http://{s}.tile.cloudmade.com/c77b2fb7bfb74f74998061abda20d58f/997/256/{z}/{x}/{y}.png',{
    attribution: '2013 &copy @ Rajat/Akshat',
    maxZoom: 18
}).addTo(map);

var marker = L.marker([51.5,-0.09], {draggable: true, opacity: 0.8}).addTo(map);

function onDragEnd(e) {
    var lat_marker = e.target._latlng.lat;
    var lng_marker = e.target._latlng.lng;      
}

var i=6;
marker.on('dragend',onDragEnd(event));

The map1 div id has been created on HTML page.

Now the problem is this function:

marker.on('dragend',onDragEnd(event));

It shows this error

ReferenceError: event is not defined

marker.on('dragend',onDragEnd(event));

But when I pass it without any argument marker.on('dragend',onDragEnd());, it works.

Also, I want to add my own parameter in the function:

marker.on('dragend',onDragEnd(i));

Where i is some simple variable. But something is wrong in this function, it doesn't work as expected.

回答1:

onDragEnd(event)

executes the function. You just need to pass in the function reference

marker.on('dragend',onDragEnd);

Using () after the function executes the function immediately. You want this method to act as a callback when the drag ends.

And event object is passed in y default, when this method is invoked. So you need not worry about passing it as an argument

function onDragEnd(event) {

To pass in the custom parameter you can try something in these lines..

for(var i=0; i < $('span').length ; i++) {
    $('span').eq(i).on('click', bindClick(i));
}

function bindClick(index) {
    return function(e) {
        dragEnd(e, index);
    }
}

function dragEnd(e, index) {
    console.log(e);
    console.log(index);
}

Code

for (var i = 0; i < $('.marker').length; i++) {
    var marker = $('.marker').eq(i);
    $('span').eq(i).on('dragend', bindDragEnd(i));
}

function bindDragEnd(index) {
    return function (e) {
        dragEnd(e, index);
    }
}

function dragEnd(e, index) {
    console.log(e);
    // you can access the marker object 
    //by accessing it like $('.marker').eq(index)
}

Check Fiddle