简体   繁体   中英

Proper formatting and distribution on multiple events for a jquery button click?

For now, on a button click I have it so that it takes in data from two textboxes, and uses it to

1) append tweets to a panel, and

2) drop pins on a map.

My next step is to have it so that on the button click, it geodecodes a location, and does the same thing. I feel like my jquery.click function is getting really big, and wanted to know if there was a standard way to "separate" it out to make it look prettier and more readable. Can you typically have javascript functions within a jquery file that are called upon, or what is the way to go?

Here is my current jquery file. As you can see it's very big but what happens is straight forward: searchbutton on click takes some values, and sets up a new map in that location, then I access my web server's information, append it to a panel, and also drop pins on a map.

$(function () {

    $("#search-button").click(function() {
        // variables for google maps
        var LatValue = parseFloat($("#searchLat").val());
        var LonValue = parseFloat($("#searchLon").val());
        var myLatLng = {lat: LatValue, lng: LonValue};

        var map = new google.maps.Map(document.getElementById('map-canvas'), {
            zoom: 12,
            center: myLatLng
        });

        $.getJSON(
            "http://localhost:3000/tw",

            {   
                geoSearchWord: $("#searchme").val(),
                geoSearchWordLat: $("#searchLat").val(),
                geoSearchWordLon: $("#searchLon").val(),
                geoSearchWordRad: $("#searchRadius").val()
            }

        ).done(function (result) {
            $("#fromTweets").empty();   

            console.log(result);
            for (i = 0; i < result.statuses.length; i++) {

                //Print out username and status
                $("#fromTweets").append('<b>' + "Username: " + '</b>' + result.statuses[i].user.screen_name + '<br/>');
                $("#fromTweets").append('<b>' + "Tweet: " + '</b>' + result.statuses[i].text + '<br/>');
                $("#fromTweets").append('<b>' + "Created at: " + '</b>' + result.statuses[i].created_at + '<br/>');

                if (result.statuses[i].geo !== null) {
                    //Print out the geolocation
                    $("#fromTweets").append('<b>' + "GeoLocation: " + '</b>' + "Lat: " + result.statuses[i].geo.coordinates[0] + " Lon: " + result.statuses[i].geo.coordinates[1] + '<br/>'+ '<br/>');

                    //dropping a new marker on the map for each tweet that has lat/lon values
                    //Multiplying by i * 0.0005 to space them out in case they are from the same gelocation while still holding
                    //the integrity of their location.
                    LatValue = parseFloat(result.statuses[i].geo.coordinates[0] + i*0.0005);
                    LonValue = parseFloat(result.statuses[i].geo.coordinates[1] + i*0.0005);
                    myLatLng = {lat: LatValue, lng: LonValue};
                    var newMarker = new google.maps.Marker({
                        position: myLatLng,
                        map: map,
                        animation: google.maps.Animation.DROP,
                    });
                } else {
                    $("#fromTweets").append('<b>' + "GeoLocation: " + '</b>' + "Cannot be identified" + '<br/>' + '<br/>')
                }
            }

        });
    });

The most simple and obvious thing you can do it so split your code by extracting independent logical blocks to functions:

Just something like this:

var map;

function combineTweetsAjaxRequestData()
{
    return {   
        geoSearchWord: $("#searchme").val(),
        geoSearchWordLat: $("#searchLat").val(),
        geoSearchWordLon: $("#searchLon").val(),
        geoSearchWordRad: $("#searchRadius").val()
    };
}

function createGMap()
{
    return new google.maps.Map(document.getElementById('map-canvas'), {
        zoom: 12,
        center: {
            lat: parseFloat($("#searchLat").val()), 
            lng: parseFloat($("#searchLon").val())
        }
    });
}

function createGMarker(coords)
{
    var coordsFixed = {
        lat: parseFloat(coords[0] + i * 0.0005),
        lng: parseFloat(coords[1] + i * 0.0005)
    };
    return new google.maps.Marker({
        position: coordsFixed,
        map: map,
        animation: google.maps.Animation.DROP,
    });
}

function clearInfo() {
    $("#fromTweets").empty();
}

function appendInfo(title, text)
{
    $("#fromTweets").append('<b>' + title + ':</b> ' + text + '<br/>');
}

function processTweet(tw)
{           
    appendInfo('Username', tw.user.screen_name);
    appendInfo('Tweet', tw.text);
    appendInfo('Created at', tw.created_at);

    if (tw.geo !== null) {
        var twCoords = tw.geo.coordinates;
        appendInfo('GeoLocation', "Lat: " + twCoords[0] + " Lon: " + twCoords[1]);
        createGMarker(twCoords);        
    } else {
        appendInfo('GeoLocation', "Cannot be identified")
    }
}

function loadTweets() {
    $.getJSON(
        "http://localhost:3000/tw",
        combineTweetsAjaxRequestData()
    ).done(function (result) {
        clearInfo();
        console.log(result);

        result.statuses.forEach(processTweet);
    });
}

$(document).ready(function () {
    map = createGMap();
    $("#search-button").click(function() {
        loadTweets();
    });
});

Now, it can be easily read as a text. Your code should be readable and understandable from the first glance. Even better, if a non-developer can read it and understand some basic concepts.

  • What happens when the page is loaded? We create a Google map control and load tweets
  • How do we load tweets? We make a AJAX request by combining request data from inputs
  • What happens when it is loaded? We clear out current information and process every tweet
  • How do we process a single tweet? We output some basic information. Then, we output geolocation if it is available. Otherwise, we output an error.

Now, if you need to add information to another source, you won't extend or modify your loadTweets method - you will extend or modify appendInfo method, because the logics of information output is encapsulated here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM