w6d4 Flashcards
Explain how DOM elements bubble
DOM events typically bubble: if an event fires on element X which lives inside element Y, then after being fired on X the event will bubble up and be fired on Y.
What is the difference between the currentTarget and the target?
The currentTarget is the element that the event handler corresponds to (i.e. a ul), and the target is what actually activates the event handler (i.e. a li)
What is event delegation?
A pattern of installing a single event handler on a parent to catch events on its children.
What does the 3 element version of jQuery#on ?
It sets up an event delegation; the first is the event, then the child element to target, then the callback.
What is the method to fire an event from within code?
jQuery#trigger
What is the object that we must define a new jQuery plugin on?
$.fn
What is an example of a simple jQuery plugin?
$.fn.greenify = function() {
this.css( “color”, “green” );
return this;
}
$( “a” ).greenify().addClass( “greenified” );
How can we prevent collisions with other JS libraries which use $?
Use an IIFE:
(function ( $ ) {
$.fn.greenify = function() { this.css( "color", "green" ); return this; };
}( jQuery ));
What is the best practice when defining methods on .fn?
Define one function on it and overload it to take different numbers/types of arguments.
How do we deal with #each?
Return it’s RESULTS (i.e. NOT Ruby!):
$.fn.myNewPlugin = function() {
return this.each(function() { // Do something to each element here. });
};
How can we set up a function to take what is (essentially) an options hash?
(function ( $ ) {
$.fn.greenify = function( options ) {
// This is the easiest way to have default options. var settings = $.extend({ // These are the defaults. color: "#556b2f", backgroundColor: "white" }, options );
// Greenify the collection based on the settings variable. return this.css({ color: settings.color, backgroundColor: settings.backgroundColor }); };
}( jQuery ));
What is a simple jQuery plugin that can show the location of a link?
(function( $ ) {
$.fn.showLinkLocation = function() { this.filter( "a" ).append(function() { return " (" + this.href + ")"; }); return this; };
}( jQuery ));
See an example of a full widget (plugin) file
(function () {
if (typeof NameApp === “undefined”) {
window.NameApp = {};
}
$.NameSearch = function (el) {
this. $el = $(el); this. $input = this.$el.find("input[name=query]"); this. $ul = this.$el.find("ul.names"); this.$input.on("input", this.render.bind(this)); this.render(); };
$.NameSearch.prototype.searchResults = function () {
return NameApp.Name.search(this.$input.val());
};
$.NameSearch.prototype.render = function () {
this.$ul.empty();
this.searchResults().forEach((function (name) { var $li = $("<li>"); $li.text(name.fullName()); this.$ul.append($li); }).bind(this)); };
$.fn.nameSearch = function () { return this.each(function () { new $.NameSearch(this); }); } })();
$(function () {
$(‘.name-search’).nameSearch();
});