Caching data using object

Caching Data API responses using object.

by FiNGAHOLiC

HTML

<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<button>Get tweet!</button>

JavaScript

// http://stackoverflow.com/questions/4869609/how-can-jquery-deferred-be-used

var tweetCache = {};

var getTweet = function(query){
    
    console.log(tweetCache[query] ? 'FROM [CACHE]' : 'FROM [AJAX]');
    
    return tweetCache[query] || $.ajax({
        url : 'http://search.twitter.com/search.json',
        dataType : 'jsonp',
        data : {
            result_type : 'recent',
            rpp : 10,
            page : 1,
            q : query
        },
        success : function(res){
            tweetCache[query] = res;
        }
    });
    
};

var fetchTweet = function(query){
    
    $.when(getTweet(query)).then(function(res){
        console.log(res);
    });
    
};

$(function(){
    
    var $button = $('button');
    
    $button.on('click', function(){
        fetchTweet('jquery');
    });

});