如何将默认选项从一种方法传递给子序列方法?
例如,我在方法中有一些默认设置init
。我想将这些设置用于其他方法,例如show
,
(function($) {
var methods = {
init: function(options) {
var defaults = {
element: "selection"
}
var options = $.extend(defaults, options);
var o = options;
alert(o.element);
},
show: function(o) {
alert(o.element);
},
hide: function() {
alert(o.element);
}
};
$.fn.plugin = 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.tooltip' );
}
};
})( jQuery );
var blah = $('#hello').plugin('show'); // TypeError: o is undefined
我想得到selection
答案……有可能吗?
编辑:
(function($) {
$.fn.plugin = 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.tooltip' );
}
};
$.fn.plugin.defaults = {
attr: 'checked',
expected: true,
onChange: function(){}
};
var methods = {
init: function(options) {
var options = $.extend({}, $.fn.plugin.defaults, options);
var o = options;
var $this = this;
$this.show();
//alert(o.attr);
},
show: function(options) {
var options = $.extend({}, $.fn.plugin.defaults, options);
var o = options;
alert(o.expected);
},
hide: function(object) {
alert(o.element);
}
};
})( jQuery );
var blah = $('#hello').plugin('show',{expected:"#hello world"});
现在我得到#hello world
(正确)
但,
var blah = $('#hello').plugin('init'); // returns nothing
我想得到true
答案,因为init
正在访问show
. 那么如何从一个方法访问其他方法呢?