How to extend a widget to include new functionality?
Let's imagine ourselves creating a jQuery widget. We're using jquery.ui.widget for the task. We want to create a simple squared div with red borders. Well, let it be our framework for any future extended widgets.
(function ($) {
$.widget('ns.redsquare', {
_create: function () {
var elem = this.element;
elem.css({
width: 100,
height: 100,
border: 'solid 1px red'
});
$(this.element).appendTo('body');
}
// probably a lot of other funct开发者_运维问答ionality follows
}
$(document).ready(function () {
$('<div/>').redsquare();
});
})(jQuery);
So, the future came. We want to extend our red square so that it contains a squared div with green borders. Certainly, the child should be a bit smaller than the parent. The question is "How to extend the widget to include new functionality?". That is, how do we extend (not change the source code of) our red square to help our green square have the parent? The code of the red square should stay intact; the green square should have its own code but include all the functionality the red square can probably offer.
NOTE: The widget example provided hereby is not a real one; it is just another unfortunately example of mine.
Use the process of subclassing explained here.
精彩评论