-1

In a tutorial I saw they used JSON to get information from twitter, and then paste in a Template (Handlebars). I'm really new with this concepts of JSON and fetching information from the server, but what confused me the most is that the anonymous function in $.JSON and $map was that they use a callback function and pass some parameters. I don´t understand where they come from and why they're referencing them. If anyone could give me a clue it would be great. Thanks

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Twiiter API</title>
</head>
<body>
    <ul class="tweets">
        <script id="tweets-template" type="text/x-handlebars-template" >
        {{#each this}}
            <li>
                <img src = "{{thumb}}" alt= "{{author}}">
                <p><a href="{{url}}">{{tweet}}</a></p>
            </li>
        {{/each}}       
        </script> 
    </ul> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.rc.1.js"></script>
    <script>
    (function(){
            var Twitter = {
                init: function(config){
                    this.url = 'http://search.twitter.com/search.json?q=' + config.query + '&callback=?';

                    this.template = config.template;
                    this.container = config.container;
                    this.fetch();
                },

                attachTemplate : function(){
                        var template = Handlebars.compile(this.template);
                        this.container.append(template (this.tweets));
                },

                fetch: function(){
                    var self = this; // This REFERS TO TWITTER  OBJECT
                    $.getJSON(this.url, function (data){
                        //$.map WILL FILTER THROUGH AN ARRAY AND FOR EACH ONE OF THOES IT WILL EXECUTE A FUNCTION
                        self.tweets =  $.map(data.results, function(tweet){
                                return {
                                    author : tweet.from_user,
                                    tweet : tweet.text,
                                    thumb: tweet.profile_image_url,
                                    url: 'http://twitter.com/' + tweet.form_user + '/status/' + tweet.id_str
                                };
                        });

                    self.attachTemplate();
                    });
                }
            };  
            Twitter.init({
                template:$('#tweets-template').html(),
                container:$('ul.tweets'),
                query: 'tutspremium'
            });
    })();
    </script>
</body>
</html>
Mike
  • 2,132
  • 3
  • 20
  • 33
Trapo
  • 17
  • 3

1 Answers1