Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

javascript - execute a function only once

I have a function which executes on click event, but the thing is that I want it to execute only once.

The function that get's executed on click represents a google map plotting to an targeted element. The function looks like this :

Cluster.prototype.initiate_map_assembling = function(target, latitude, longitude) {
    var canvas = $(target).children();
    var coordinates = new google.maps.LatLng(latitude, longitude);

    var options = {
        zoom: 9,
        center: coordinates,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map($(canvas)[0], options);

    var marker = new google.maps.Marker({
        position: coordinates,
        map: map
    });
};

And I'm running it on click event like this :

Cluster.prototype.initiate_google_maps_action = function() {
    var self = this;
    return $(this.maps_wrapper_class).each(function(index, element) {
        var canvas = $(element).parents().eq(3).find(self.map_canvas_wrapper_class);
        return $(element).on('click', function(ev) {
            var latitude = $(element).attr('data-latitude');
            var longitude = $(element).attr('data-longitude');
            self.initiate_map_assembling(canvas, latitude, longitude);
            ($(canvas).hasClass('selected')) ? $(canvas).removeClass('selected') : $(canvas).addClass('selected');
            ev.preventDefault();
        });
    });
};

What I want to achieve is stop the plotting each time I click the button, because it's only needed once since I'm only hiding the container div and not destroying it. So how could I do that ? I tried with temporary variables added when the function executes ( and setting it as true after the first time and as false when initiated ) and returning false if the temporary variable is true, but with little success as I could not return false inside the plotting function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you could bind click only once like:

$(document).one('click', function(e) {
    //do your code here
});

OR

$('#someBtn').click(function(){    
    if ($(this).attr('data-once')!='already_clicked' ){
        //your code here
        $(this).attr('data-once', 'already_clicked');
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...