Web前端最新jQuery UI widget源码解析,前端入门

前端资料汇总

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

我一直觉得技术面试不是考试,考前背背题,发给你一张考卷,答完交卷等通知。

首先,技术面试是一个 认识自己 的过程,知道自己和外面世界的差距。

更重要的是,技术面试是一个双向了解的过程,要让对方发现你的闪光点,同时也要 试图去找到对方的闪光点,因为他以后可能就是你的同事或者领导,所以,面试官问你有什么问题的时候,不要说没有了,要去试图了解他的工作内容、了解这个团队的氛围。
找工作无非就是看三点:和什么人、做什么事、给多少钱,要给这三者在自己的心里划分一个比例。
最后,祝愿大家在这并不友好的环境下都能找到自己心仪的归宿。

  1. //创建一个自定义的伪类选择器

  2. //如 $(‘:ui-menu’) 则表示选择定义了ui-menu插件的元素

  3. $.expr[“:”][fullName.toLowerCase()] = function(elem) {

  4. return !!$.data(elem, fullName);

  5. };

  6. // 判定命名空间对象是否存在,没有的话 则创建一个空对象

  7. KaTeX parse error: Undefined control sequence: \[ at position 1: \̲[̲namespace\] = [namespace] || {};

  8. //这里存一份旧版的插件,如果这个插件已经被使用或者定义了

  9. existingConstructor = $[namespace][name];

  10. //这个是插件实例化的主要部分

  11. //constructor存储了插件的实例,同时也创建了基于命名空间的对象

  12. //如$.ui.menu

  13. constructor = $[namespace][name] = function(options, element) {

  14. // allow instantiation without “new” keyword

  15. //允许直接调用命名空间上的方法来创建组件

  16. //比如:$.ui.menu({},‘#id’) 这种方式创建的话,默认没有new 实例化。因为_createWidget是prototype上的方法,需要new关键字来实例化

  17. //通过 调用 $.ui.menu 来实例化插件

  18. if (!this._createWidget) {

  19. console.info(this)

  20. return new constructor(options, element);

  21. }

  22. // allow instantiation without initializing for simple inheritance

  23. // must use “new” keyword (the code above always passes args)

  24. //如果存在参数,则说明是正常调用插件

  25. //_createWidget是创建插件的核心方法

  26. if (arguments.length) {

  27. this._createWidget(options, element);

  28. }

  29. };

  30. // extend with the existing constructor to carry over any static properties

  31. //合并对象,将旧插件实例,及版本号、prototype合并到constructor

  32. $.extend(constructor, existingConstructor, {

  33. version: prototype.version,

  34. // copy the object used to create the prototype in case we need to

  35. // redefine the widget later

  36. //创建一个新的插件对象

  37. //将插件实例暴露给外部,可用户修改及覆盖

  38. _proto: $.extend({}, prototype),

  39. // track widgets that inherit from this widget in case this widget is

  40. // redefined after a widget inherits from it

  41. _childConstructors: []

  42. });

  43. //实例化父类 获取父类的  prototype

  44. basePrototype = new base();

  45. // we need to make the options hash a property directly on the new instance

  46. // otherwise we’ll modify the options hash on the prototype that we’re

  47. // inheriting from

  48. //这里深复制一份options

  49. basePrototype.options = $.widget.extend({}, basePrototype.options);

  50. //在传入的ui原型中有方法调用this._super 和this.__superApply会调用到base上(最基类上)的方法

  51. $.each(prototype, function(prop, value) {

  52. //如果val不是function 则直接给对象赋值字符串

  53. if (!$.isFunction(value)) {

  54. proxiedPrototype[prop] = value;

  55. return;

  56. }

  57. //如果val是function

  58. proxiedPrototype[prop] = (function() {

  59. //两种调用父类函数的方法

  60. var _super = function() {

  61. //将当期实例调用父类的方法

  62. return base.prototype[prop].apply(this, arguments);

  63. },

  64. _superApply = function(args) {

  65. return base.prototype[prop].apply(this, args);

  66. };

  67. return function() {

  68. var __super = this._super,

  69. __superApply = this._superApply,

  70. returnValue;

  71. //                console.log(prop, value,this,this._super,‘===’)

  72. //                debugger;

  73. //在这里调用父类的函数

  74. this._super = _super;

  75. this._superApply = _superApply;

  76. returnValue = value.apply(this, arguments);

  77. this._super = __super;

  78. this._superApply = __superApply;

  79. //                console.log(this,value,returnValue,prop,‘===’)

  80. return returnValue;

  81. };

  82. })();

  83. });

  84. //    console.info(proxiedPrototype)

  85. //    debugger;

  86. //这里是实例化获取的内容

  87. constructor.prototype = $.widget.extend(basePrototype, {

  88. // TODO: remove support for widgetEventPrefix

  89. // always use the name + a colon as the prefix, e.g., draggable:start

  90. // don’t prefix for widgets that aren’t DOM-based

  91. widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name

  92. }, proxiedPrototype, {

  93. //重新把constructor指向 constructor 变量

  94. constructor: constructor,

  95. namespace: namespace,

  96. widgetName: name,

  97. widgetFullName: fullName

  98. });

  99. // If this widget is being redefined then we need to find all widgets that

  100. // are inheriting from it and redefine all of them so that they inherit from

  101. // the new version of this widget. We’re essentially trying to replace one

  102. // level in the prototype chain.

  103. //这里判定插件是否被使用了。一般来说,都不会被使用的。

  104. //因为插件的开发者都是我们自己,呵呵

  105. if (existingConstructor) {

  106. $.each(existingConstructor._childConstructors, function(i, child) {

  107. var childPrototype = child.prototype;

  108. // redefine the child widget using the same prototype that was

  109. // originally used, but inherit from the new version of the base

  110. $.widget(childPrototype.namespace + “.” + childPrototype.widgetName, constructor, child._proto);

  111. });

  112. // remove the list of existing child constructors from the old constructor

  113. // so the old child constructors can be garbage collected

  114. delete existingConstructor._childConstructors;

  115. } else {

  116. //父类添加当前插件的实例 主要用于作用域链查找 不至于断层

  117. base._childConstructors.push(constructor);

  118. }

  119. //将此方法挂在jQuery对象上

  120. $.widget.bridge(name, constructor);

  121. return constructor;

  122. };

  123. //扩展jq的extend方法,实际上类似$.extend(true,…) 深复制

  124. $.widget.extend = function(target) {

  125. var input = widget_slice.call(arguments, 1),

  126. inputIndex = 0,

  127. inputLength = input.length,

  128. key, value;

  129. for (; inputIndex < inputLength; inputIndex++) {

  130. for (key in input[inputIndex]) {

  131. value = input[inputIndex][key];

  132. if (input[inputIndex].hasOwnProperty(key) && value !== undefined) {

  133. // Clone objects

  134. if ($.isPlainObject(value)) {

  135. target[key] = KaTeX parse error: Undefined control sequence: \[ at position 22: …inObject(target\̲[̲key\]) ? .widget.extend({}, target[key], value) :

  136. // Don’t extend strings, arrays, etc. with objects

  137. $.widget.extend({}, value);

  138. // Copy everything else by reference

  139. } else {

  140. target[key] = value;

  141. }

  142. }

  143. }

  144. }

  145. return target;

  146. };

  147. //bridge 是设计模式的一种,这里将对象转为插件调用

  148. $.widget.bridge = function(name, object) {

  149. var fullName = object.prototype.widgetFullName || name;

  150. //这里就是插件了

  151. //这部分的实现主要做了几个工作,也是制作一个优雅的插件的主要代码

  152. //1、初次实例化时将插件对象缓存在dom上,后续则可直接调用,避免在相同元素下widget的多实例化。简单的说,就是一个单例方法。

  153. //2、合并用户提供的默认设置选项options

  154. //3、可以通过调用插件时传递字符串来调用插件内的方法。如:$(‘#id’).menu(‘hide’) 实际就是实例插件并调用hide()方法。

  155. //4、同时限制外部调用“_”下划线的私有方法

  156. $.fn[name] = function(options) {

  157. var isMethodCall = typeof options === “string”,

  158. args = widget_slice.call(arguments, 1),

  159. returnValue = this;

  160. // allow multiple hashes to be passed on init.

  161. //可以简单认为是$.extend(true,options,args[0],…),args可以是一个参数或是数组

  162. options = !isMethodCall && args.length ? $.widget.extend.apply(null, [options].concat(args)) : options;

  163. //这里对字符串和对象分别作处理

  164. if (isMethodCall) {

  165. this.each(function() {

  166. var methodValue, instance = $.data(this, fullName);

  167. //如果传递的是instance则将this返回。

  168. if (options === “instance”) {

  169. returnValue = instance;

  170. return false;

  171. }

  172. if (!instance) {

  173. return $.error("cannot call methods on " + name + " prior to initialization; " + “attempted to call method '” + options + “'”);

  174. }

  175. //这里对私有方法的调用做了限制,直接调用会抛出异常事件

  176. if (!$.isFunction(instance[options]) || options.charAt(0) === “_”) {

  177. return $.error(“no such method '” + options + “’ for " + name + " widget instance”);

  178. }

  179. //这里是如果传递的是字符串,则调用字符串方法,并传递对应的参数.

  180. //比如插件有个方法hide(a,b); 有2个参数:a,b

  181. //则调用时$(‘#id’).menu(‘hide’,1,2);//1和2 分别就是参数a和b了。

  182. methodValue = instance[options].apply(instance, args);

  183. if (methodValue !== instance && methodValue !== undefined) {

  184. returnValue = methodValue && methodValue.jquery ? returnValue.pushStack(methodValue.get()) : methodValue;

  185. return false;

  186. }

  187. });

  188. } else {

  189. this.each(function() {

  190. var instance = $.data(this, fullName);

  191. if (instance) {

  192. instance.option(options || {});

  193. //这里每次都调用init方法

  194. if (instance._init) {

  195. instance._init();

  196. }

  197. } else {

  198. //缓存插件实例

  199. $.data(this, fullName, new object(options, this));

  200. }

  201. });

  202. }

  203. return returnValue;

  204. };

  205. };

  206. //这里是真正的widget基类

  207. $.Widget = function( /* options, element */ ) {};

  208. $.Widget._childConstructors = [];

  209. $.Widget.prototype = {

  210. widgetName: “widget”,

  211. //用来决定事件的名称和插件提供的callbacks的关联。

  212. // 比如dialog有一个close的callback,当close的callback被执行的时候,一个dialogclose的事件被触发。

  213. // 事件的名称和事件的prefix+callback的名称。widgetEventPrefix 默认就是控件的名称,但是如果事件需要不同的名称也可以被重写。

  214. // 比如一个用户开始拖拽一个元素,我们不想使用draggablestart作为事件的名称,我们想使用dragstart,所以我们可以重写事件的prefix。

  215. // 如果callback的名称和事件的prefix相同,事件的名称将不会是prefix。

  216. // 它阻止像dragdrag一样的事件名称。

  217. widgetEventPrefix: “”,

  218. defaultElement: “

    ”,

  219. //属性会在创建模块时被覆盖

  220. options: {

  221. disabled: false,

  222. // callbacks

  223. create: null

  224. },

  225. _createWidget: function(options, element) {

  226. element = $(element || this.defaultElement || this)[0];

  227. this.element = $(element);

  228. this.uuid = widget_uuid++;

  229. this.eventNamespace = “.” + this.widgetName + this.uuid;

  230. this.options = $.widget.extend({}, this.options, this._getCreateOptions(), options);

  231. this.bindings = $();

  232. this.hoverable = $();

  233. this.focusable = $();

  234. if (element !== this) {

  235. //            debugger

  236. $.data(element, this.widgetFullName, this);

  237. this._on(true, this.element, {

  238. remove: function(event) {

  239. if (event.target === element) {

  240. this.destroy();

  241. }

  242. }

  243. });

  244. this.document = $(element.style ?

  245. // element within the document

  246. element.ownerDocument :

  247. // element is window or document

  248. element.document || element);

  249. this.window = $(this.document[0].defaultView || this.document[0].parentWindow);

  250. }

  251. this._create();

  252. //创建插件时,有个create的回调

  253. this._trigger(“create”, null, this._getCreateEventData());

  254. this._init();

  255. },

  256. _getCreateOptions: $.noop,

  257. _getCreateEventData: $.noop,

  258. _create: $.noop,

  259. _init: $.noop,

  260. //销毁模块:去除绑定事件、去除数据、去除样式、属性

  261. destroy: function() {

  262. this._destroy();

  263. // we can probably remove the unbind calls in 2.0

  264. // all event bindings should go through this._on()

  265. this.element.unbind(this.eventNamespace).removeData(this.widgetFullName)

  266. // support: jquery <1.6.3

  267. // http://bugs.jquery.com/ticket/9413

  268. .removeData($.camelCase(this.widgetFullName));

  269. this.widget().unbind(this.eventNamespace).removeAttr(“aria-disabled”).removeClass(

  270. this.widgetFullName + "-disabled " + “ui-state-disabled”);

  271. // clean up events and states

  272. this.bindings.unbind(this.eventNamespace);

  273. this.hoverable.removeClass(“ui-state-hover”);

  274. this.focusable.removeClass(“ui-state-focus”);

  275. },

  276. _destroy: $.noop,

  277. widget: function() {

  278. return this.element;

  279. },

  280. //设置选项函数

  281. option: function(key, value) {

  282. var options = key,

  283. parts, curOption, i;

  284. if (arguments.length === 0) {

  285. // don’t return a reference to the internal hash

  286. //返回一个新的对象,不是内部数据的引用

  287. return $.widget.extend({}, this.options);

  288. }

  289. if (typeof key === “string”) {

  290. // handle nested keys, e.g., “foo.bar” => { foo: { bar: ___ } }

  291. options = {};

  292. parts = key.split(“.”);

  293. key = parts.shift();

  294. if (parts.length) {

  295. curOption = options[key] = $.widget.extend({}, this.options[key]);

  296. for (i = 0; i < parts.length - 1; i++) {

  297. curOption[parts[i]] = curOption[parts[i]] || {};

  298. curOption = curOption[parts[i]];

  299. }

  300. key = parts.pop();

  301. if (arguments.length === 1) {

  302. return curOption[key] === undefined ? null : curOption[key];

  303. }

  304. curOption[key] = value;

  305. } else {

  306. if (arguments.length === 1) {

  307. return this.options[key] === undefined ? null : this.options[key];

  308. }

  309. options[key] = value;

  310. }

  311. }

  312. this._setOptions(options);

  313. return this;

  314. },

  315. _setOptions: function(options) {

  316. var key;

  317. for (key in options) {

  318. this._setOption(key, options[key]);

  319. }

  320. return this;

  321. },

  322. _setOption: function(key, value) {

  323. this.options[key] = value;

  324. if (key === “disabled”) {

  325. this.widget().toggleClass(this.widgetFullName + “-disabled”, !! value);

  326. // If the widget is becoming disabled, then nothing is interactive

  327. if (value) {

  328. this.hoverable.removeClass(“ui-state-hover”);

  329. this.focusable.removeClass(“ui-state-focus”);

  330. }

  331. }

  332. return this;

  333. },

  334. enable: function() {

  335. return this._setOptions({

  336. disabled: false

  337. });

  338. },

  339. disable: function() {

  340. return this._setOptions({

  341. disabled: true

  342. });

  343. },  
    最后

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

最后写上我自己一直喜欢的一句名言:世界上只有一种真正的英雄主义就是在认清生活真相之后仍然热爱它

  • 11
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值