jquery helper methods
pushStack, end, each, plugin, extend, proxy
HTML
<input id="btn" type="button" value="format"/>
<div class="stack" id="1">1</div>
<div class="stack" id="2">2</div>
<div class="stack" id="3">3</div>
<div class="stack" id="4">4</div>
<div class="stack" id="5">5</div>
<div class="stack" id="6">6</div><br/><br/>
<input id="btnExtend" type="button" value="Extend Demo"/>
<div id="divExtend"></div>
<input id="btnWithoutProxy" type="button" value="Without Proxy Demo"/>
<input id="btnWithProxy" type="button" value="With Proxy Demo"/>
<div id="divProxy"></div>
JavaScript
$.fn.alternateItem = function() {
var arr = [];
$.each(this, function(idx, item) {
if (idx % 2 == 0) arr.push(item);
});
return this.pushStack(arr, "alternateItem", "");
};
$("#btn").click(function() {
//the end function removes the last filter from stack and returns the previous state of elements
console.log($("div.stack").alternateItem().end());
$("div.stack").alternateItem().css("color", "Red").end().css("font-weight", "Bold");
});
// extending objects
//extend can be used to extend objects
//in this example after extending the targetobject is able to call methods on the source object
var sourceObj = {
actions: {
actionA: function() {
$("#divExtend").append("action A <br/>");
},
actionB: function() {
$("#divExtend").append("action B source <br/>");
}
}
};
var targetObj = {
actions: {
actionB: function() {
$("#divExtend").append("action B target <br/>");
},
actionC: function() {
$("#divExtend").append("action C <br/>");
}
}
};
$("#btnExtend").click(function() {
$.extend(true, targetObj, sourceObj); //true means deep copy otherwise targetObj would have lost its actions and had it replaced with sourceObj since the name "actions" is conflicting. Because of true a merge happened. however since even one of the methods actionB was also same in both objects, the source actionB overrode the target actionB
targetObj.actions.actionA();
targetObj.actions.actionB();
targetObj.actions.actionC();
});
//proxy
//proxy is used to change the context of a function in which it will be executed. used to set the value of this keyword in an event handler
var handler = {
type:"crazy type",
clickHandler:function(event){$("#divProxy").empty().append(this.type);}
};
$("#btnWithoutProxy").click(handler.clickHandler);
$("#btnWithProxy").click($.proxy(handler.clickHandler, handler));