jquery ui widget 源碼分析

來源:互聯網
上載者:User

jquery ui widget 源碼分析

jquery ui 的所有組件都是基於一個簡單,可重用的widget。

這個widget是jquery ui的核心部分,實用它能實現一致的API,建立有狀態的外掛程式,而無需關心外掛程式的內部轉換。

$.widget( name, base, prototype )

widget一共有2或3個參數。base為可選。

這裡之所以把base放在第二個參數裡,主要是因為這樣寫代碼更直觀一些。(因為後面的prototype 是個代碼非常長的大對象)。

name:第一個參數是一個包含一個命名空間和組件名稱的字串,通過”.”來分割。
命名空間必須有,它指向widget prototype儲存的全域jQuery對象。
如果命名空間沒有,widget factory將會為你產生。widget name是外掛程式函數和原型的真實名稱,
比如: jQuery.widget( “demo.multi”, {…} ) 將會產生 jQuery.demo , jQuery.demo.multi , and jQuery.demo.multi.prototype .

base:第二個參數(可選)是 widget prototype繼承於什麼對象。
例如jQuery UI有一個“mouse”的外掛程式,它可以作為其他的外掛程式提供的基礎。
為了實現這個所有的基於mouse的外掛程式比如draggable,
droppable可以這麼做: jQuery.widget( "ui.draggable", $.ui.mouse, {...} );
如果沒有這個參數,widget預設繼承自“base widget” jQuery.Widget(注意jQuery.widget 和 jQuery.Widget不同) 。

prototype:最後一個參數是一個物件常值,它會轉化為所有widget執行個體的prototype。widget factory會產生屬性鏈,串連到她繼承的widget的prototype。一直到最基本的 jQuery.Widget。

一旦你調用jQuery.widget,它會在jQuery prototype ( jQuery.fn )上產生一個新的可用方法對應於widget的名字,比如我們這個例子jQuery.fn.multi。 .fn方法是包含Dom元素的jquery對象和你產生的 widget prototyp執行個體的介面,為每一個jQuery對象產生一個新的widget的執行個體。

/*! * jQuery UI Widget @VERSION * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/jQuery.widget/ *///這裡判定是否支援amd or cmd 模式(function(factory) {if (typeof define === "function" && define.amd) {// AMD. Register as an anonymous module.define(["jquery"], factory);} else {// Browser globalsfactory(jQuery);}}(function($) {var widget_uuid = 0,//外掛程式的執行個體化數量widget_slice = Array.prototype.slice; //數組的slice方法,這裡的作用是將參賽arguments 轉為真正的數組//清除外掛程式的資料及緩衝$.cleanData = (function(orig) {return function(elems) {for (var i = 0, elem;(elem = elems[i]) != null; i++) {try {// 重寫cleanData方法,調用後觸發每個元素的remove事件$(elem).triggerHandler("remove");// http://bugs.jquery.com/ticket/8235} catch (e) {}}orig(elems);};})($.cleanData);/** * widgetFactory 方法,用於建立外掛程式 * @param name 包含命名空間的外掛程式名稱,格式 xx.xxx * @param base 需要繼承的ui組件 * @param prototype 外掛程式的實際代碼 * @returns {Function} */$.widget = function(name, base, prototype) {var fullName, //外掛程式全稱existingConstructor, //原有的建構函式constructor, //當前建構函式basePrototype, //父類的Prototype// proxiedPrototype allows the provided prototype to remain unmodified// so that it can be used as a mixin for multiple widgets (#8876)proxiedPrototype = {},//可調用父類方法_spuer的prototype對象,擴充於prototypenamespace = name.split(".")[0];name = name.split(".")[1];fullName = namespace + "-" + name;//如果只有2個參數  base預設為Widget類,組件預設會繼承base類的所有方法if (!prototype) {prototype = base;base = $.Widget;}//    console.log(base, $.Widget)// create selector for plugin//建立一個自訂的偽類別選取器//如 $(':ui-menu') 則表示選擇定義了ui-menu外掛程式的元素$.expr[":"][fullName.toLowerCase()] = function(elem) {return !!$.data(elem, fullName);};// 判定命名空間對象是否存在,沒有的話 則建立一個Null 物件$[namespace] = $[namespace] || {};//這裡存一份舊版的外掛程式,如果這個外掛程式已經被使用或者定義了existingConstructor = $[namespace][name];//這個是外掛程式執行個體化的主要部分//constructor儲存了外掛程式的執行個體,同時也建立了基於命名空間的對象//如$.ui.menuconstructor = $[namespace][name] = function(options, element) {// allow instantiation without "new" keyword//允許直接調用命名空間上的方法來建立組件//比如:$.ui.menu({},'#id') 這種方式建立的話,預設沒有new 執行個體化。因為_createWidget是prototype上的方法,需要new關鍵字來執行個體化//通過 調用 $.ui.menu 來執行個體化外掛程式if (!this._createWidget) {console.info(this)return new constructor(options, element);}// allow instantiation without initializing for simple inheritance// must use "new" keyword (the code above always passes args)//如果存在參數,則說明是正常調用外掛程式//_createWidget是建立外掛程式的核心方法if (arguments.length) {this._createWidget(options, element);}};// extend with the existing constructor to carry over any static properties//合并對象,將舊外掛程式執行個體,及版本號碼、prototype合并到constructor$.extend(constructor, existingConstructor, {version: prototype.version,// copy the object used to create the prototype in case we need to// redefine the widget later//建立一個新的外掛程式對象//將外掛程式執行個體暴露給外部,可使用者修改及覆蓋_proto: $.extend({}, prototype),// track widgets that inherit from this widget in case this widget is// redefined after a widget inherits from it_childConstructors: []});//執行個體化父類 擷取父類的  prototypebasePrototype = new base();// we need to make the options hash a property directly on the new instance// otherwise we'll modify the options hash on the prototype that we're// inheriting from//這裡深複製一份optionsbasePrototype.options = $.widget.extend({}, basePrototype.options);//在傳入的ui原型中有方法調用this._super 和this.__superApply會調用到base上(最基類上)的方法$.each(prototype, function(prop, value) {//如果val不是function 則直接給對象賦值字串if (!$.isFunction(value)) {proxiedPrototype[prop] = value;return;}//如果val是functionproxiedPrototype[prop] = (function() {//兩種調用父類函數的方法var _super = function() {//將當期執行個體調用父類的方法return base.prototype[prop].apply(this, arguments);},_superApply = function(args) {return base.prototype[prop].apply(this, args);};return function() {var __super = this._super,__superApply = this._superApply,returnValue;//                console.log(prop, value,this,this._super,'===')//                debugger;//在這裡調用父類的函數this._super = _super;this._superApply = _superApply;returnValue = value.apply(this, arguments);this._super = __super;this._superApply = __superApply;//                console.log(this,value,returnValue,prop,'===')return returnValue;};})();});//    console.info(proxiedPrototype)//    debugger;//這裡是執行個體化擷取的內容constructor.prototype = $.widget.extend(basePrototype, {// TODO: remove support for widgetEventPrefix// always use the name + a colon as the prefix, e.g., draggable:start// don't prefix for widgets that aren't DOM-basedwidgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name}, proxiedPrototype, {//重新把constructor指向 constructor 變數constructor: constructor,namespace: namespace,widgetName: name,widgetFullName: fullName});// If this widget is being redefined then we need to find all widgets that// are inheriting from it and redefine all of them so that they inherit from// the new version of this widget. We're essentially trying to replace one// level in the prototype chain.//這裡判定外掛程式是否被使用了。一般來說,都不會被使用的。//因為外掛程式的開發人員都是我們自己,呵呵if (existingConstructor) {$.each(existingConstructor._childConstructors, function(i, child) {var childPrototype = child.prototype;// redefine the child widget using the same prototype that was// originally used, but inherit from the new version of the base$.widget(childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto);});// remove the list of existing child constructors from the old constructor// so the old child constructors can be garbage collecteddelete existingConstructor._childConstructors;} else {//父類添加當前外掛程式的執行個體 主要用於範圍鏈尋找 不至於斷層base._childConstructors.push(constructor);}//將此方法掛在jQuery對象上$.widget.bridge(name, constructor);return constructor;};//擴充jq的extend方法,實際上類似$.extend(true,..) 深複製$.widget.extend = function(target) {var input = widget_slice.call(arguments, 1),inputIndex = 0,inputLength = input.length,key, value;for (; inputIndex < inputLength; inputIndex++) {for (key in input[inputIndex]) {value = input[inputIndex][key];if (input[inputIndex].hasOwnProperty(key) && value !== undefined) {// Clone objectsif ($.isPlainObject(value)) {target[key] = $.isPlainObject(target[key]) ? $.widget.extend({}, target[key], value) :// Don't extend strings, arrays, etc. with objects$.widget.extend({}, value);// Copy everything else by reference} else {target[key] = value;}}}}return target;};//bridge 是設計模式的一種,這裡將對象轉為外掛程式調用$.widget.bridge = function(name, object) {var fullName = object.prototype.widgetFullName || name;//這裡就是外掛程式了//這部分的實現主要做了幾個工作,也是製作一個優雅的外掛程式的主要代碼//1、初次執行個體化時將外掛程式對象緩衝在dom上,後續則可直接調用,避免在相同元素下widget的多執行個體化。簡單的說,就是一個單例方法。//2、合并使用者提供的預設設定選項options//3、可以通過調用外掛程式時傳遞字串來調用外掛程式內的方法。如:$('#id').menu('hide') 實際就是執行個體外掛程式並調用hide()方法。//4、同時限制外部調用“_”底線的私人方法$.fn[name] = function(options) {var isMethodCall = typeof options === "string",args = widget_slice.call(arguments, 1),returnValue = this;// allow multiple hashes to be passed on init.//可以簡單認為是$.extend(true,options,args[0],...),args可以是一個參數或是數組options = !isMethodCall && args.length ? $.widget.extend.apply(null, [options].concat(args)) : options;//這裡對字串和對象分別作處理if (isMethodCall) {this.each(function() {var methodValue, instance = $.data(this, fullName);//如果傳遞的是instance則將this返回。if (options === "instance") {returnValue = instance;return false;}if (!instance) {return $.error("cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'");}//這裡對私人方法的調用做了限制,直接調用會拋出例外狀況事件if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {return $.error("no such method '" + options + "' for " + name + " widget instance");}//這裡是如果傳遞的是字串,則調用字串方法,並傳遞對應的參數.//比如外掛程式有個方法hide(a,b); 有2個參數:a,b//則調用時$('#id').menu('hide',1,2);//1和2 分別就是參數a和b了。methodValue = instance[options].apply(instance, args);if (methodValue !== instance && methodValue !== undefined) {returnValue = methodValue && methodValue.jquery ? returnValue.pushStack(methodValue.get()) : methodValue;return false;}});} else {this.each(function() {var instance = $.data(this, fullName);if (instance) {instance.option(options || {});//這裡每次都調用init方法if (instance._init) {instance._init();}} else {//快取區外掛程式執行個體$.data(this, fullName, new object(options, this));}});}return returnValue;};};//這裡是真正的widget基類$.Widget = function( /* options, element */ ) {};$.Widget._childConstructors = [];$.Widget.prototype = {widgetName: "widget",//用來決定事件的名稱和外掛程式提供的callbacks的關聯。// 比如dialog有一個close的callback,當close的callback被執行的時候,一個dialogclose的事件被觸發。// 事件的名稱和事件的prefix+callback的名稱。widgetEventPrefix 預設就是控制項的名稱,但是如果事件需要不同的名稱也可以被重寫。// 比如一個使用者開始拖拽一個元素,我們不想使用draggablestart作為事件的名稱,我們想使用dragstart,所以我們可以重寫事件的prefix。// 如果callback的名稱和事件的prefix相同,事件的名稱將不會是prefix。// 它阻止像dragdrag一樣的事件名稱。widgetEventPrefix: "",defaultElement: "",//屬性會在建立模組時被覆蓋options: {disabled: false,// callbackscreate: null},_createWidget: function(options, element) {element = $(element || this.defaultElement || this)[0];this.element = $(element);this.uuid = widget_uuid++;this.eventNamespace = "." + this.widgetName + this.uuid;this.options = $.widget.extend({}, this.options, this._getCreateOptions(), options);this.bindings = $();this.hoverable = $();this.focusable = $();if (element !== this) {//            debugger$.data(element, this.widgetFullName, this);this._on(true, this.element, {remove: function(event) {if (event.target === element) {this.destroy();}}});this.document = $(element.style ?// element within the documentelement.ownerDocument :// element is window or documentelement.document || element);this.window = $(this.document[0].defaultView || this.document[0].parentWindow);}this._create();//建立外掛程式時,有個create的回調this._trigger("create", null, this._getCreateEventData());this._init();},_getCreateOptions: $.noop,_getCreateEventData: $.noop,_create: $.noop,_init: $.noop,//銷毀模組:去除綁定事件、去除資料、去除樣式、屬性destroy: function() {this._destroy();// we can probably remove the unbind calls in 2.0// all event bindings should go through this._on()this.element.unbind(this.eventNamespace).removeData(this.widgetFullName)// support: jquery <1.6.3// http://bugs.jquery.com/ticket/9413.removeData($.camelCase(this.widgetFullName));this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName + "-disabled " + "ui-state-disabled");// clean up events and statesthis.bindings.unbind(this.eventNamespace);this.hoverable.removeClass("ui-state-hover");this.focusable.removeClass("ui-state-focus");},_destroy: $.noop,widget: function() {return this.element;},//設定選項函數option: function(key, value) {var options = key,parts, curOption, i;if (arguments.length === 0) {// don't return a reference to the internal hash//返回一個新的對象,不是內部資料的引用return $.widget.extend({}, this.options);}if (typeof key === "string") {// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }options = {};parts = key.split(".");key = parts.shift();if (parts.length) {curOption = options[key] = $.widget.extend({}, this.options[key]);for (i = 0; i < parts.length - 1; i++) {curOption[parts[i]] = curOption[parts[i]] || {};curOption = curOption[parts[i]];}key = parts.pop();if (arguments.length === 1) {return curOption[key] === undefined ? null : curOption[key];}curOption[key] = value;} else {if (arguments.length === 1) {return this.options[key] === undefined ? null : this.options[key];}options[key] = value;}}this._setOptions(options);return this;},_setOptions: function(options) {var key;for (key in options) {this._setOption(key, options[key]);}return this;},_setOption: function(key, value) {this.options[key] = value;if (key === "disabled") {this.widget().toggleClass(this.widgetFullName + "-disabled", !! value);// If the widget is becoming disabled, then nothing is interactiveif (value) {this.hoverable.removeClass("ui-state-hover");this.focusable.removeClass("ui-state-focus");}}return this;},enable: function() {return this._setOptions({disabled: false});},disable: function() {return this._setOptions({disabled: true});},_on: function(suppressDisabledCheck, element, handlers) {var delegateElement, instance = this;// no suppressDisabledCheck flag, shuffle argumentsif (typeof suppressDisabledCheck !== "boolean") {handlers = element;element = suppressDisabledCheck;suppressDisabledCheck = false;}// no element argument, shuffle and use this.elementif (!handlers) {handlers = element;element = this.element;delegateElement = this.widget();} else {// accept selectors, DOM elementselement = delegateElement = $(element);this.bindings = this.bindings.add(element);}$.each(handlers, function(event, handler) {function handlerProxy() {// allow widgets to customize the disabled handling// - disabled as an array instead of boolean// - disabled class as method for disabling individual partsif (!suppressDisabledCheck && (instance.options.disabled === true || $(this).hasClass("ui-state-disabled"))) {return;}return (typeof handler === "string" ? instance[handler] : handler).apply(instance, arguments);}// copy the guid so direct unbinding worksif (typeof handler !== "string") {handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++;}var match = event.match(/^([\w:-]*)\s*(.*)$/),eventName = match[1] + instance.eventNamespace,selector = match[2];if (selector) {delegateElement.delegate(selector, eventName, handlerProxy);} else {element.bind(eventName, handlerProxy);}});},_off: function(element, eventName) {eventName = (eventName || "").split(" ").join(this.eventNamespace + " ") + this.eventNamespace;element.unbind(eventName).undelegate(eventName);},_delay: function(handler, delay) {function handlerProxy() {return (typeof handler === "string" ? instance[handler] : handler).apply(instance, arguments);}var instance = this;return setTimeout(handlerProxy, delay || 0);},_hoverable: function(element) {this.hoverable = this.hoverable.add(element);this._on(element, {mouseenter: function(event) {$(event.currentTarget).addClass("ui-state-hover");},mouseleave: function(event) {$(event.currentTarget).removeClass("ui-state-hover");}});},_focusable: function(element) {this.focusable = this.focusable.add(element);this._on(element, {focusin: function(event) {$(event.currentTarget).addClass("ui-state-focus");},focusout: function(event) {$(event.currentTarget).removeClass("ui-state-focus");}});},_trigger: function(type, event, data) {var prop, orig, callback = this.options[type];data = data || {};event = $.Event(event);event.type = (type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type).toLowerCase();// the original event may come from any element// so we need to reset the target on the new eventevent.target = this.element[0];// copy original event properties over to the new eventorig = event.originalEvent;if (orig) {for (prop in orig) {if (!(prop in event)) {event[prop] = orig[prop];}}}this.element.trigger(event, data);return !($.isFunction(callback) && callback.apply(this.element[0], [event].concat(data)) === false || event.isDefaultPrevented());}};$.each({show: "fadeIn",hide: "fadeOut"}, function(method, defaultEffect) {$.Widget.prototype["_" + method] = function(element, options, callback) {if (typeof options === "string") {options = {effect: options};}var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect;options = options || {};if (typeof options === "number") {options = {duration: options};}hasOptions = !$.isEmptyObject(options);options.complete = callback;if (options.delay) {element.delay(options.delay);}if (hasOptions && $.effects && $.effects.effect[effectName]) {element[method](options);} else if (effectName !== method && element[effectName]) {element[effectName](options.duration, options.easing, callback);} else {element.queue(function(next) {$(this)[method]();if (callback) {callback.call(element[0]);}next();});}};});return $.widget;}));


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.