年少不知愁滋味,為賦新詞常說愁。
年少不聽李宗盛,聽懂已是不惑年。
本期編輯 小蟲巨蟹。
jQuery 插件寫法
最簡單的寫法如下:
$.fn.myPluginName = function() {
// your plugin logic
}
如下寫法不會和別的庫沖突,推薦:
(function( $ ){
$.fn.myPluginName = function() {
// your plugin logic
};
})( jQuery );
插件參數和自定義參數的合并,用 $.extend
,也可以用 Object.assign
。
;( function( $ ){
$.fn.extend( {
pluginname: function( options ) {
this.defaults = {};
// 插件參數和自定義參數的合并
var settings = $.extend( {}, this.defaults, options );
return this.each( function() {
var $this = $( this );
});
}
});
})( jQuery );
寫 jQuery 插件的模板如下:
;(function ( $, window, document, undefined ) {
var pluginName = 'defaultPluginName',
defaults = {
propertyName: "value"
};
function Plugin( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype.init = function () {
// 初始化代碼
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new Plugin( this, options ));
}
});
}
})( jQuery, window, document );
組件之間通信,用自定義事件的方式,可以做到很好的代碼解耦:
;(function ( $, window, document, undefined ) {
$.widget("ao.eventStatus", {
options: {
},
_create : function() {
var self = this;
//self.element.addClass( "my-widget" );
//subscribe to 'myEventStart'
self.element.bind( "myEventStart", function( e ) {
console.log("event start");
});
//subscribe to 'myEventEnd'
self.element.bind( "myEventEnd", function( e ) {
console.log("event end");
});
//unsubscribe to 'myEventStart'
//self.element.unbind( "myEventStart", function(e){
///console.log("unsubscribed to this event");
//});
},
destroy: function(){
$.Widget.prototype.destroy.apply( this, arguments );
},
});
})( jQuery, window , document );
讓寫的 jQuery 的插件既支持 AMD 又支持 CommonJS 的方式見這里。
文章推薦
《基于 Node、WebSocket 的手機控制電腦實例》
背景
如果不關注底層協議細節,WebSocket 基板上一句話就可以說清楚:WebSocket 是建立在傳輸層 TCP 之上,并且依賴于 HTTP 的應用層協議,它的出現主要是為了彌補 HTTP 協議中,服務器端無法主動推送消息到客戶端的缺陷。但是這樣對初學者的幫助遠遠不夠,不如直接有實例來的直觀。
概要
- 實例介紹、效果預覽
- 實現思路
- 代碼實現