[英]Create jQuery plugin with configuration settings
我一直在使用以下設計模式來創建 jQuery 插件。 我很確定我從 jQuery 主頁獲得了這個概念,但是,它似乎不再在那里發布。
我最近嘗試訪問init()
方法以外的方法(即someOtherMethod ()
)中的settings
變量,但由於未定義settings
而遇到錯誤。 我看到了原因,因為settings
與init()
方法是隔離的。
如果我將settings
移到此方法之外,則可以從不同的方法訪問它,但是,應用插件時的每個實例都沒有其唯一的設置變量,這是不可接受的。 例如, $('#id1, #id2').myPlugin({x:111});
應該有一個通用的settings
變量,但是$('#id1').myPlugin({x:111}); $('#id2').myPlugin({x:222});
$('#id1').myPlugin({x:111}); $('#id2').myPlugin({x:222});
每個人都應該有自己獨特的設置變量。
以下面的設計模式為起點,如何從與插件關聯的所有方法訪問settings
變量,但每次應用插件時都有一個唯一的settings
變量?
(function( $ ){
var defaults={
x : 123,
y : 321
};
// var settings={}; //Should settings be defined here???
var methods = {
init : function( options ) {
var settings = $.extend(defaults, options || {});
//settings = $.extend(defaults, options || {}); //Should settings just be updated and not defined here?
return this.each(function(){
//whatever
});
},
someOtherMethod : function() {
return $(this).each(function(){
//do whatever and use settings variable as applicable
})
},
};
$.fn.myPlugin = function(method) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.myPlugin' );
}
};
}( jQuery ));
$('#id1, #id2').myPlugin({x:111}); //Sets x=111 in settings for both
$('#id3').myPlugin({x:333}); //Sets x=333 in settings.
$('#id3').myPlugin('someOtherMethod'); //Will have access to x=333 in settings.
您將要為每個元素保存設置對象,以便設置將在不同的選擇器中保持不變。 最好的方法是使用jQuery.data
將設置對象附加到元素。 這樣,每次選擇元素時,設置都會保持不變,而不管它是如何選擇的。
然后,在someOtherMethod
的.each
調用中,您可以在元素上使用jQuery.data
訪問此數據。
此外,每個單獨的元素都需要一個單獨的設置對象以避免覆蓋共享設置,因此:
var settings = $.extend(defaults, options || {});
將需要替換為:
var settings = $.extend({}, defaults, options || {});
否則, defaults
對象每次都會被新的設置屬性覆蓋,並在所有元素之間共享。
在這個例子中,我創建了一個變量名internalPrefix
,值為'_myPlugin'
作為使用jQuery.data
保存數據的jQuery.data
。 我在底部添加了一些測試來展示如何以不同的方式初始化它,但是可以調用該方法並且仍然知道用於在元素上初始化的設置。
#工作示例:
(function( $ ){ var defaults={ x : 123, y : 321 }; //A variable to save the setting data under. var internalPrefix = '_myPlugin'; var methods = { init : function( options ) { return this.each(function() { //Setup the settings object. var settings = $.extend({}, defaults, options || {}); //Save the settings to the element. $(this).data(internalPrefix, settings); }); }, someOtherMethod : function() { return this.each(function() { //Get the existing settings. var settings = $(this).data(internalPrefix); //Example: $('<code></code>').text(JSON.stringify(settings)).appendTo(this); }) }, }; $.fn.myPlugin = function(method) { if ( methods[method] ) { return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.myPlugin' ); } }; }( jQuery )); //Initialize the plugin different ways. $('.group-1').myPlugin(); $('.group-2').myPlugin({ x : 42, y : 1337 }); //Cal the methods on those different ways. $('p').myPlugin('someOtherMethod');
<p class="group-1">group 1</p> <p class="group-1">group 1</p> <p class="group-2">group 2</p> <p class="group-2">group 2</p> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
更新,添加{}
作為$.extend()
第一個參數
但是,如果您想保留兩個原始對象,則可以通過傳遞一個空對象作為目標來實現:
var object = $.extend({}, object1, object2);
嘗試將defaults
為methods
屬性,在init
定義settings
var settings = $.extend({}, methods.defaults, options || {});
在調用.each()
之前使用settings
設置this
元素.data()
.each()
return this.data(settings).each(function() {})
然后每個元素的settings
都是唯一的; 訪問使用$(this).data()
返回defaults
,如果options
不作為參數傳遞到$.fn.myPlugin
,更新defaults
如果options
作為參數傳遞給$.fn.myPlugin
(function($) { var defaults = { x: 123, y: 321 }; var methods = { init: function(options) { // extend `methods.defaults` with `options` var settings = $.extend({}, methods.defaults, options || {}); return this.data(settings).each(function() { //whatever console.log("init", this.id, $(this).data()); }); }, someOtherMethod: function() { return $(this).each(function() { //do whatever and use settings variable as applicable console.log("someOtherMethod", this.id, $(this).data()); }) }, }; // set `defaults` as property of `methods` methods.defaults = defaults; $.fn.myPlugin = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.myPlugin'); } }; }(jQuery)); $('#id1, #id2').myPlugin({ x: 111 }); $("#id1").myPlugin({ y: 222 }); $("#id2").myPlugin({ y: 333 }); $("#id2").myPlugin("someOtherMethod");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div id="id1"></div> <div id="id2"></div>
jsfiddle http://jsfiddle.net/z28wwnLh/1/
只是快速刺一下,但這行不通嗎? 還是我完全沒有抓住重點?
(function ($) {
var defaults = {
x: 123,
y: 321
};
$.fn.myPlugin = {
init: function (opts) {
var settings = $.extend(defaults, opts || {});
$.each(settings, function (a, b) {
console.log(a, ':', b);
});
},
someOtherMethod: function (opts) {
var settings = $.extend(defaults, opts || {});
$.each(settings, function (a,b) {
console.log(a,':', b);
});
}
};
}(jQuery));
$('#id1, #id2').myPlugin.init({ x: 111 }); //Sets x=111 in settings for both
$('#id3').myPlugin.init({ x: 333 }); //Sets x=333 in settings.
$('#id3').myPlugin.someOtherMethod({ x: 223 });
$('#id1').myPlugin.someOtherMethod({ a: 223 });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.