我怎样才能通过默认选项从一种方法到子序列方法?
例如,我有一些默认设置 in the 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
作为答案...可能吗?
EDIT:
(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 );
参考 http://ryanflorence.com/use-your-fn-jquery-namespace/
var blah = $('#hello').plugin('show',{expected:"#hello world"});
现在我明白了#hello world
(正确的)
but,
var blah = $('#hello').plugin('init'); // returns nothing
我想要得到true
作为答案,因为init
正在访问show
。那么我该如何访问其他方法 from a method?