Skip to content

Instantly share code, notes, and snippets.

@tilomitra
Created November 10, 2010 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tilomitra/671242 to your computer and use it in GitHub Desktop.
Save tilomitra/671242 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Getting data back with Datasource</title>
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.2.0/build/cssreset/reset-min.css">
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.2.0/build/cssbase/base-min.css">
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.2.0/build/cssgrids/grids-min.css">
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body class="yui3-skin-sam">
<div id="ac">
<input type="search" id="ac-input" placeholder="Movie Name">
<input type="button" id="reviewBtn" value="Retrieve!">
<p>
<input type="button" id="datatableBtn" value="Show Datatable!">
<input type="button" id="chartsBtn" value="Show Chart!">
</p>
</div>
<div id="overlay">
<div id="widget" class="yui3-overlay-bd"></div>
</div>
<div id="loader" class="yui3-1"></div>
<div id="results" class="yui3-1"><div class="placeholder">Type a movie name above and retrieve information.</div></div>
<!--You need YUI3.3.0PR1 atleast to get Autocomplete to work. Change the yui-min.js file URL below as needed-->
<script type="text/javascript" charset="utf-8" src="../../yui3/build/yui/yui-min.js"></script>
<script type="text/javascript" src="http://trippbridges.com/yui3-gallery/build/gallery-charts/gallery-charts.js" charset="utf-8"></script>
<script type="text/javascript" src="demo-4.js"></script>
</body>
</html>
/* ========================================================================= *
* @author tilomitra@gmail.com *
* *
* Description: A demonstration of how to use Datasource to pull in *
* YQL data in YUI3. Shows how to parse using DataSchema plugin, normalize *
* using parser object, and display content using the new Charts + *
* Autocomplete widgets *
* *
* Requirements: YUI3.3.0PR1 and higher, APIKEY from tmdb.org *
* NOTE: THIS CODE IS MEANT FOR DEMO PURPOSES. DO NOT USE IN PRODUCTION. *
* YOUR APIKEY WILL BE VISIBLE. *
* ========================================================================= */
YUI().use(
'autocomplete',
'autocomplete-filters',
'autocomplete-highlighters',
'event-delegate',
'datasource',
'datatable',
'gallery-charts',
'overlay',
function(Y) {
//Nodes that we will be working with
var search = Y.one('#ac-input'),
reviewBtn = Y.one('#reviewBtn'),
results = Y.one('#results'),
loader = Y.Node.create('<img src="loader.gif">'),
overlay,
//template for an overlay div with a nested widget div
OVERLAY_TEMPLATE = '<div id="overlay"><div id="widget" class="yui3-overlay-bd"></div></div>',
RESULT_TEMPLATE = '<div id="results" class="yui3-1"></div>',
//template for each movie result
MOVIE_TEMPLATE = '<div class="movie yui3-1"><div class="yui3-u-1-6 movie-img"><img src="{img}"></div><div class="yui3-u-3-5 movie-desc"><h2>{name}</h2><p><strong>Overview: </strong>{movieOverview}</p></div><div class="yui3-u-1-6 movie-extras"><a class="readmore" id="{imdbId}" href="{movieUrl}">View Page</a><br/><strong>Certification: </strong>{certification}<br/><strong>Votes: </strong>{votes}<br/><strong>Rating: </strong>{rating}</div><div class="clearfix yui3-u"></div></div>',
AUTH = {
TMDB_APIKEY: 'insert-your-api-key-here'
},
//object of URLs that we will be using
URL = {
YQL: 'https://query.yahooapis.com/v1/public/yql?format=json&',
//select movies.movie.name from themoviedb.movie.search where api_key='your-api-key' and movie='{query}'
MOVIE: "q=select%20movies.movie.name%20from%20themoviedb.movie.search%20where%20api_key%3D'"+AUTH.TMDB_APIKEY+"'%20and%20movie%3D%22{query}%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&",
//select movies.movie from themoviedb.movie.search where api_key='your-api-key' and movie='{movie}'
REVIEW: "q=select%20*%20from%20themoviedb.movie.search%20where%20api_key%3D'"+AUTH.TMDB_APIKEY+"'%20and%20movie%3D'{movie}'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&"
},
//Generates a dynamic movie request encoded URL that we can pass in to get the details on a particular movie
dyn_movieRequest = function() {
return Y.Lang.sub(URL.REVIEW, {movie: encodeURIComponent(search.get('value'))})
},
//Instantiate DataSource
dataSource = new Y.DataSource.Get({
source: URL.YQL
}),
/* ---------------------
* Autocomplete Set up
* ---------------------
*/
autoComplete = new Y.AutoComplete({
inputNode: '#ac-input',
//This method is to accomodate for the fact that when you get 1 response back, result is no longer an array, but a property
resultListLocator: function(response) {
response = response && response[0];
var results = response && response.query && response.query.results && response.query.results.OpenSearchDescription,
values;
if (results && !Y.Lang.isArray(results)) {
results = [results];
}
return results || [];
},
resultTextLocator: 'movies.movie.name',
requestTemplate: URL.MOVIE,
source: dataSource,
resultHighlighter: "phraseMatch",
resultFilters: "phraseMatch",
render: true
});
autoComplete.get('inputNode').focus();
/* ---------------------
* DataSource set up
* ---------------------
*/
dataSource.plug(Y.Plugin.DataSourceCache, {max:20});
dataSource.on('request',function(e) {
if (e.request === dyn_movieRequest()) {
reviewBtn.setAttrs({disabled: true, value: 'Retrieving...'});
Y.one('#loader').appendChild(loader);
}
});
dataSource.on('response',function(e) {
if (e.request === dyn_movieRequest()) {
reviewBtn.set('disabled', false).set('value', 'Get Reviews!');
Y.one('#loader').removeChild(loader);
DATA = e.response.results;
}
});
/* ---------------------
* On Movie Select
* ---------------------
*/
reviewBtn.on('click', function() {
dataSource.plug(
Y.Plugin.DataSourceJSONSchema,
{
schema: {
resultListLocator: "query.results.OpenSearchDescription.movies.movie",
resultFields: [
{key: "name"},
{key: "id"},
{key: "tagline"},
{key: "overview"},
{key: "popularity", parser:"number"},
{key: "imdb_id"},
{key: "url"},
{key: "votes", parser:"number"},
{key: "rating", parser:"number"},
{key: "released", parser:"date"},
{key: "trailer"},
{key: "certification", parser: function(e) {
if (!e) return 'Not certified';
else return e;
}
},
{key: "images", parser:function(e) {
//Make sure an object containing image arrays is returned, and the array has the image we want
//array of different images where [0] is the largest, and size decreases as index increases
if (Y.Lang.isObject(e) && e.image[3] !== undefined) {
e = e.image[3];
}
//Otherwise, put a dummy image in its place
else {
e = {url: "http://dummyimage.com/100x130", width:"100"};
}
return e;
}
}
]
}
}
);
dataSource.sendRequest({
request: dyn_movieRequest(),
callback: {
success: displayMovieDetails,
failure: function(e) {
alert(e.error.message);
this.unplug(Y.Plugin.DataSourceJSONSchema);
}
}
});
});
Y.one('#datatableBtn').on('click', function() {
destroyOverlay();
var widgetDiv = Y.one('#widget');
var myCols = [
{key: "name", label:"Name", sortable:true},
{key:"released", label:"Opening Date", sortable:true},
{key:"votes", label:"Votes", sortable:true}
];
var dataTable = new Y.DataTable.Base({
columnset:myCols,
recordset: DATA,
width:500
}).plug(Y.Plugin.DataTableSort);
createOverlay(dataTable.get('width'),700);
dataTable.render("#widget");
});
Y.one("#chartsBtn").on('click', function() {
destroyOverlay();
var widgetDiv = Y.one('#widget');
var axes = {
votes: {
keys: ["votes"],
roundingUnit: 10,
position: 'left',
type: 'numeric'
},
name: {
styles: {
label: {
rotation: 90
}
},
type: "category",
keys:["name"]
}
};
var mychart = new Y.Chart({
type:"column",
seriesKeys:["votes"],
axes: axes,
width: 700,
height: 400,
horizontalGridlines: {
styles: {
line: {
color: '#ccc'
}
}
},
styles: {
graph: {
background: {
fill: {
color:'#ccc'
}
}
},
series: {
votes: {
marker: {
width: 60,
fill: {
color: 'blue'
}
}
}
},
tooltip: {
}
},
dataProvider:DATA
});
widgetDiv.setStyle('height', mychart.get('height')+'px');
createOverlay(mychart.get('width'), mychart.get('height'));
mychart.render('#widget');
});
function displayMovieDetails(e) {
var results = Y.one('#results'),
len = e.response.results.length,
i = 0,
movie,
str = '';
//Unplug the schema so we can use the same datasource for autocomplete again
dataSource.unplug(Y.Plugin.DataSourceJSONSchema);
if (results.hasChildNodes) {
results.replace(Y.Node.create(RESULT_TEMPLATE));
results = Y.one('#results');
}
for (; i<len; i++) {
movie = e.response.results[i];
sub = {
img: movie.images.url,
name: movie.name,
movieOverview: movie.overview,
imdbId: movie.imdb_id,
movieUrl: movie.url,
movieId: movie.id,
rating: movie.rating,
certification: movie.certification,
votes: movie.votes
};
str += Y.Lang.sub(MOVIE_TEMPLATE, sub);
}
results.appendChild(str);
setUpReadMore();
}
function setUpReadMore() {
Y.all('.readmore').on('click', function(e) {
e.preventDefault();
});
}
function createOverlay(w,h) {
overlay = new Y.Overlay({
srcNode:"#overlay",
width:w+50+'px',
centered: true
});
overlay.render();
Y.one('#results').on('click', function() {
destroyOverlay();
});
}
function destroyOverlay() {
if (overlay) {
overlay.destroy();
}
Y.one('#results').insertBefore(OVERLAY_TEMPLATE);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment