Web Tech/jQuery
jQuery 플러그인 디자인 패턴
jaiyah
2015. 6. 30. 14:15
jQuery 플러그인 디자인 패턴
jQuery 플러그인 설계시에 기본적으로 고려해야 할 점들을 알아 보겠습니다.
1. 플러그인 이름
2. 플러그인 제작 기본 패턴
(function())(); 을 활용한 $ 별칭을 보호
체이닝 설정
3. 사용자 정의 옵션 설정
4. 네임스페이스
플러그인 이름 작성
jquery.{{플러그인이름}}.js 또는 jquery.{{플러그인이름}}.1.0.0.js
플러그인 제작 기본 패턴
(function(global, $){
'use strict';
$.fn[{{pluginName}}] = function() {
var _this = this;
return _this;
// return _this.each(function(index, item){});
// return _this.pushStack(element);
};
})(window, window.jQuery);
플러그인 사용자 정의 옵션 설정
default 옵션을 외부에서 수정하지 못하는 패턴
(function(global, $){
'use strict';
var settings = {};
var defaults = {};
$.fn[{{PluginName}}] = function(options) {
var _this = this;
// $.extend()를 활용한 객체 병합
$.extend(settings, defaults, options);
// 체이닝 설정
return _this;
};
})(window, window.jQuery);
default 옵션을 외부에서 수정가능하게 하는 패턴
(function(global, $){
'use strict';
var settings = {};
$.fn[{{플러그인이름}}] = function(options) {
var _this = this;
// $.extend()를 활용한 객체 병합
$.extend(settings, this[{{플러그인이름}}].defaults, options);
return _this;
};
// 외부에서 $.fn[{{플러그인이름}}].defaults 기본 값 변경 가능
$.fn[{{플러그인이름}}].defaults = {};
})(window, window.jQuery);
Jaehee's e-room