/ Gists / JavaScript

Gists - JavaScript

On gists

Slick slider with thumbs

JavaScript jQuery

example.js #

// https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.5.9/slick.min.js
// //cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js

 $('.slider-for').slick({
   slidesToShow: 1,
   slidesToScroll: 1,
   arrows: false,
   fade: true,
   asNavFor: '.slider-nav'
 });
 $('.slider-nav').slick({
   slidesToShow: 3,
   slidesToScroll: 1,
   asNavFor: '.slider-for',
   dots: true,
   focusOnSelect: true
 });

 $('a[data-slide]').click(function(e) {
   e.preventDefault();
   var slideno = $(this).data('slide');
   $('.slider-nav').slick('slickGoTo', slideno - 1);
 });

On gists

JS constructor + init immediately

JavaScript-OOP JavaScript

demo.js #

1)
var Abc = function(aProperty,bProperty){
    this.aProperty = aProperty;
    this.bProperty = bProperty;
    this.init = function(){
        // Do things here.
    }
    this.init();
}; 
var currentAbc = new Abc(obj,obj);


2)
var Abc = function(aProperty,bProperty){
   function privateInit(){ console.log(this.aProperty);}   
   this.aProperty = aProperty;
   this.bProperty = bProperty;

   privateInit.apply(this);
};


3)
var Abc = function(aProperty,bProperty){
    this.aProperty = aProperty;
    this.bProperty = bProperty;

    //init
    (function () {
        // Perform some operation
    }.call(this));
}; 
var currentAbc = new Abc(obj,obj);

On gists

local/session storage - get/set object wrapper

JavaScript JSON

get-setObject.js #

Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObject = function(key) {
    var value = this.getItem(key);
    return value && JSON.parse(value);
}

On gists

Closures in JavaScript

JavaScript

in-loop.js #

// https://diskuse.jakpsatweb.cz/?action=vthread&forum=8&topic=103393

for(var i=0; stylNameArray.length>i; i++) {
   (function(){
     var n = i;
     neco[i].onclick = function() {
      zmenaStylu("styl_pozadi_oken_0" + n);
    }
   })();
} 


for(var i=0; stylNameArray.length>i; i++) {
   (function(i){
     neco[i].onclick = function() {
      zmenaStylu("styl_pozadi_oken_0" + i);
    }
   })(i);
}

On gists

jQuery.stringify() utility

JavaScript

jQuery.stringify.js #


/**
 * converted stringify() to jQuery plugin.
 * serializes a simple object to a JSON formatted string.
 * Note: stringify() is different from jQuery.serialize() which URLEncodes form elements

 * UPDATES:
 *      Added a fix to skip over Object.prototype members added by the prototype.js library
 * USAGE:
 *  jQuery.ajax({
 *	    data : {serialized_object : jQuery.stringify (JSON_Object)},
 *		success : function (data) {
 *
 *		}
 *   });
 *
 * CREDITS: http://blogs.sitepointstatic.com/examples/tech/json-serialization/json-serialization.js
 */
jQuery.extend({
    stringify  : function stringify(obj) {
        var t = typeof (obj);
        if (t != "object" || obj === null) {
            // simple data type
            if (t == "string") obj = '"' + obj + '"';
            return String(obj);
        } else {
            // recurse array or object
            var n, v, json = [], arr = (obj && obj.constructor == Array);

            for (n in obj) {
                v = obj[n];
                t = typeof(v);
                if (obj.hasOwnProperty(n)) {
                    if (t == "string") v = '"' + v + '"'; else if (t == "object" && v !== null) v = jQuery.stringify(v);
                    json.push((arr ? "" : '"' + n + '":') + String(v));
                }
            }
            return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
        }
    }
});

On gists

Events - target/currentTarget/delegateTarget

JavaScript jQuery

example.html #

// CLICK on button

<div class="box">
    <button>Button</button>
</div>


$( "body" ).on( "click", ".box", function(e) {
    e.delegateTarget; // body
    e.currentTarget;  // .box
    e.target;         // button
});

On gists

PubSub events

JavaScript jQuery

2.html #

<!doctype html>
<html>
<head>
	<meta charset=utf-8>
	<title>Custom Events</title>
</head>
<body>

<h1>Hi There</h1>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>


<script>
	
// PubSub
(function( $ ) {
	var o = $( {} );
	$.each({
		trigger: 'publish',
		on: 'subscribe',
		off: 'unsubscribe'
	}, function( key, val ) {
		jQuery[val] = function() {
			o[key].apply( o, arguments );
		};
	});
})( jQuery );
$.getJSON('http://search.twitter.com/search.json?q=dogs&callback=?', function( results) { 
	$.publish( 'twitter/results', results );
});
// ...
$.subscribe( 'twitter/results', function( e, results ) {
	$('body').html(
		$.map( results.results, function( obj, index) {
			return '<li>' + obj.text + '</li>';
		}).join('')
	);
});
</script>

</body>
</html>

On gists

Twitter plugin by JW

JavaScript jQuery jQuery-plugins

twitter.js #

// Utility
if ( typeof Object.create !== 'function' ) {
	Object.create = function( obj ) {
		function F() {};
		F.prototype = obj;
		return new F();
	};
}

(function( $, window, document, undefined ) {
	var Twitter = {
		init: function( options, elem ) {
			var self = this;

			self.elem = elem;
			self.$elem = $( elem );

			self.url = 'https://api.twitter.com/1.1/search/tweets.json';

			self.search = ( typeof options === 'string' )
				? options
				: options.search;

			self.options = $.extend( {}, $.fn.queryTwitter.options, options );

			self.refresh( 1 );
		},

		refresh: function( length ) {
			var self = this;

			setTimeout(function() {
				self.fetch().done(function( results ) {
					results = self.limit( results.results, self.options.limit );

					self.buildFrag( results );

					self.display();

					if ( typeof self.options.onComplete === 'function' ) {
						self.options.onComplete.apply( self.elem, arguments );
					}

					if ( self.options.refresh ) {
						self.refresh();
					}
				});
			}, length || self.options.refresh );
		},

		fetch: function() {
			return $.ajax({
				url: this.url,
				data: { q: this.search },
				dataType: 'jsonp'
			});
		},

		buildFrag: function( results ) {
			var self = this;

			self.tweets = $.map( results, function( obj, i) {
				return $( self.options.wrapEachWith ).append ( obj.text )[0];
			});
		},

		display: function() {
			var self = this;

			if ( self.options.transition === 'none' || !self.options.transition ) {
				self.$elem.html( self.tweets ); // that's available??
			} else {
				self.$elem[ self.options.transition ]( 500, function() {
					$(this).html( self.tweets )[ self.options.transition ]( 500 );
				});
			}
		},

		limit: function( obj, count ) {
			return obj.slice( 0, count );
		}
	};

	$.fn.queryTwitter = function( options ) {
		return this.each(function() {
			var twitter = Object.create( Twitter );
			
			twitter.init( options, this );

			$.data( this, 'queryTwitter', twitter );
		});
	};

	$.fn.queryTwitter.options = {
		search: '@tutspremium',
		wrapEachWith: '<li></li>',
		limit: 10,
		refresh: null,
		onComplete: null,
		transition: 'fadeToggle'
	};

})( jQuery, window, document );

On gists

Twitter object - @Jeffrey Wawy

JavaScript jQuery

index.html #

<!doctype html>
<html>
<head>
	<meta charset=utf-8>
	<title>Twitter</title>
	<style>
	body { width: 600px; margin: auto; }
	ul { list-style: none; }
	li { padding-bottom: 1em; }
	img { float: left; padding-right: 1em; }
	a { text-decoration: none; color: #333; }
	</style>
</head>
<body>

<ul id="biebster-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/1.7.1/jquery.min.js"></script>

<script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.6.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;

			$.getJSON( this.url, function( data ) {
				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.from_user + '/status/' + tweet.id_str
					};
				});

				// For future lessons, research $.deferred, viewers. :)
				self.attachTemplate(); 
			});
		}
	};

	Twitter.init({
		template: $('#tweets-template').html(),
		container: $('#biebster-tweets'),
		query: 'Justin Bieber'
	});

})();

</script>


</body>
</html>









On gists

Jquery plugin with events

JavaScript jQuery

demo.html #


What about using triggers? Does anyone know any drawback using them? The benefit is that all internal variables are accessible via the triggers, and the code is very simple.

See on jsfiddle.

Example usage
<div id="mydiv">This is the message container...</div>

<script>
    var mp = $("#mydiv").messagePlugin();

    // the plugin returns the element it is called on
    mp.trigger("messagePlugin.saySomething", "hello");

    // so defining the mp variable is not needed...
    $("#mydiv").trigger("messagePlugin.repeatLastMessage");
</script>