Created
March 18, 2013 05:38
-
-
Save Fauntleroy/5185259 to your computer and use it in GitHub Desktop.
An (almost) practical example of custom JavaScript constructors.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var PlaylistItem = function( params ){ | |
// ensure params exists | |
params = params || {}; | |
// cache a reference to this | |
var playlist_item = this; | |
// attach arguments to new PlaylistItem instance | |
this.title = params.title; | |
this.artist = params.artist; | |
this.thumbnail = params.thumbnail; | |
this.duration = params.duration; | |
// return a human readable version of the duration | |
this.getPrettyDuration = function(){ | |
var seconds = playlist_item.duration % 60; | |
var minutes = parseInt( playlist_item.duration / 60 ); | |
return minutes +':'+ seconds; | |
}; | |
// create playlist item DOM element | |
var $playlist_item = $('<li><img src="'+ this.thumbnail +'" /><h6>'+ this.title +'</h6><em>'+ this.artist +'</em><var>'+ this.getPrettyDuration() +'</var><a href="#remove">x</a></li>'); | |
// bind playlist item removal | |
$playlist_item.on( 'click', 'a[href="#remove"]', function( e ){ | |
e.preventDefault(); | |
$playlist_item.remove(); | |
}); | |
// add DOM element to DOM | |
$('#playlist').append( $playlist_item ); | |
}; | |
$(function(){ | |
// data | |
var artist = 'Konami'; | |
var thumbnail = 'http://3.bp.blogspot.com/-4HnRUKAE1g0/ToSm3AdqWiI/AAAAAAAAAjg/cAi4tnRL0go/s1600/mgs1.jpg'; | |
var tracks = [{ | |
title: 'Metal Gear Solid Main Theme', | |
duration: 2 * 60 + 44 | |
}, { | |
title: 'Introduction', | |
duration: 57 | |
}, { | |
title: 'Discovery', | |
duration: 5 * 60 + 5 | |
}, { | |
title: 'Cavern', | |
duration: 3 * 60 + 12 | |
}, { | |
title: 'Intruder 1', | |
duration: 2 * 60 + 5 | |
}, { | |
title: 'Encounter', | |
duration: 2 * 60 + 21 | |
}]; | |
// loop through each item in tracks | |
for( var i in tracks ){ | |
var track = tracks[i]; | |
new PlaylistItem({ | |
title: track.title, | |
artist: artist, | |
thumbnail: thumbnail, | |
duration: track.duration | |
}); | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<style> | |
#playlist li img { | |
width: 100px; | |
} | |
</style> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> | |
<script src="./constructing.js"></script> | |
</head> | |
<body> | |
<ul id="playlist"></ul> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment