{ Hello Magento 2 }

解决 Magento 2 应用问题,更注重深度挖掘。(ง •̀_•́)ง

0%

jQuery Plugin and Widget

创建 jQuery Plugin

方法一 在 jQuery 命名空间上添加方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<head>
<title>jQuery plugin</title>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
</head>
<body>
<script type="text/javascript">
$.sayHello = function() {
console.log('Hello');
};


$.extend({
sayHi: function(name) {
console.log('Hi,' + (name ? name : 'ThankIT') + '!');
}
});
$.sayHello();
$.sayHi();
</script>
</body>
</html>

效果: jquery plugin 此种方法扩展了 jQuery 本身,但它不能选中 DOM 元素。

方法二 在 $.fn 上添加方法

在写插件之前,我们先了解下 jQuery 是怎么工作的。

1
$( "a" ).css( "color", "red" );

这是很基础的 jQuery 代码。当你用 $ 选中元素的时候,它会返回 jQuery 对象,返回的这个 jQuery 对象就包含 css() 方法,还有被选中的元素。 jQuery 对象是从 $.fn (jQuery.prototype 的别名)对象获得方法的。所以,我们可以在 $.fn 方法上添加方法来扩展 jQuery object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html>
<head>
<title>jQuery plugin</title>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
</head>
<body>
<h1 id="hello">Hello</h1>
<script type="text/javascript">
// case 1
$.sayHello = function() {
console.log('Hello');
};
$.extend({
sayHi: function(name) {
console.log('Hi,' + (name ? name : 'ThankIT') + '!');
}
});
$.sayHello();
$.sayHi();

// 在 jQuery 上扩展的方法无法选中元素
// Uncaught TypeError: $(...).sayHi is not a function
// $( "h1" ).sayHi();

// case 2
// 需要返回 this 以支持链式调用
$.fn.greenify = function() {
return this.css( "color", "green" );
};
$.fn.extend({
italic: function() {
return this.css("font-style","italic");
}
});

$( "h1" ).greenify();
$( "h1" ).italic();

</script>
</body>
</html>

效果: jquery plugin 参考官方文档 jquery plugins

安全的插件结构

1
2
3
;(function($,window,document,undefined){
// 插件代码
})(jQuery,window,document);

用自调用匿名函数包裹代码,形成一个作用域,避免对全局命名空间的污染。 使用 ; 是为了避免:前面的代码没有以分号结尾,引入我们的 js 后,导致报错无法执行。 比如:

1
2
3
4
5
6
7
8
9
var foo=function(){
//别人的代码
}//注意这里没有用分号结尾

//开始我们的代码。。。
(function(){
//我们的代码。。
alert('Hello!');
})();

参考 jQuery插件开发精品教程,让你的jQuery提升一个台阶

创建 jQuery Widget

jQuery UI 官方文档 大部分 jQuery 插件是无状态的,完成某个动作就结束了。但是有些插件是有状态的,他们有生命周期和状态,widget factory 定义了如何创建和销毁他们,如何获取和设置选项,调用方法以及监听小部件触发的事件。这样的规范会让使用者更容易使用。 例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
<!DOCTYPE html>
<html>
<head>
<title>jQuery plugin</title>
<link href="https://cdn.bootcss.com/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/jqueryui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div>
<div id="my-widget1">color me</div>
<div id="my-widget2">color me</div>
<div id="my-widget3">color me</div>
<button id="disable">Toggle disabled option</button>
<button id="green">Go green</button>
</div>
<style>
.custom-colorize {
font-size: 20px;
position: relative;
width: 75px;
height: 75px;
}
.custom-colorize-changer {
font-size: 10px;
position: absolute;
right: 0;
bottom: 0;
}
</style>
<script type="text/javascript">
$( function() {
// the widget definition, where "custom" is the namespace,
// "colorize" the widget name
$.widget( "custom.colorize", {
// default options
options: {
red: 255,
green: 0,
blue: 0,

// Callbacks
change: null,
random: null
},

// The constructor
_create: function() {
this.element
// add a class for theming
.addClass( "custom-colorize" );

this.changer = $( "<button>", {
text: "change",
"class": "custom-colorize-changer"
})
.appendTo( this.element )
.button();

// Bind click events on the changer button to the random method
this._on( this.changer, {
// _on won't call random when widget is disabled
click: "random"
});
this._refresh();
},

// Called when created, and later when changing options
_refresh: function() {
this.element.css( "background-color", "rgb(" +
this.options.red +"," +
this.options.green + "," +
this.options.blue + ")"
);

// Trigger a callback/event
this._trigger( "change" );
},

// A public method to change the color to a random value
// can be called directly via .colorize( "random" )
random: function( event ) {
var colors = {
red: Math.floor( Math.random() * 256 ),
green: Math.floor( Math.random() * 256 ),
blue: Math.floor( Math.random() * 256 )
};

// Trigger an event, check if it's canceled
if ( this._trigger( "random", event, colors ) !== false ) {
this.option( colors );
}
},

// Events bound via _on are removed automatically
// revert other modifications here
_destroy: function() {
// remove generated elements
this.changer.remove();

this.element
.removeClass( "custom-colorize" )
.enableSelection()
.css( "background-color", "transparent" );
},

// _setOptions is called with a hash of all options that are changing
// always refresh when changing options
_setOptions: function() {
// _super and _superApply handle keeping the right this-context
this._superApply( arguments );
this._refresh();
},

// _setOption is called for each individual option that is changing
_setOption: function( key, value ) {
// prevent invalid color values
if ( /redgreenblue/.test(key) && (value < 0 value > 255) ) {
return;
}
this._super( key, value );
}
});

// Initialize with default options
$( "#my-widget1" ).colorize();

// Initialize with two customized options
$( "#my-widget2" ).colorize({
red: 60,
blue: 60
});

// Initialize with custom green value
// and a random callback to allow only colors with enough green
$( "#my-widget3" ).colorize( {
green: 128,
random: function( event, ui ) {
return ui.green > 128;
}
});

// Click to toggle enabled/disabled
$( "#disable" ).on( "click", function() {
// use the custom selector created for each widget to find all instances
// all instances are toggled together, so we can check the state from the first
if ( $( ":custom-colorize" ).colorize( "option", "disabled" ) ) {
$( ":custom-colorize" ).colorize( "enable" );
} else {
$( ":custom-colorize" ).colorize( "disable" );
}
});

// Click to set options after initialization
$( "#green" ).on( "click", function() {
$( ":custom-colorize" ).colorize( "option", {
red: 64,
green: 250,
blue: 8
});
});
} );
</script>
</body>
</html>

jquery widget