Reputation: 579
Let's say this is the initialization of the plugin:
$(document).ready(function() {
$("#tree").fname({
animSpeed: 0
});
});
Now, I want to call another method and still keep that animSpeed value:
$('#tree').fname('expand');
However, with my current code, the animSpeed value is lost and the default one is used instead in the expand method call (it works in init). How could I change this?
Current Code:
;(function($){
$.fn.fname = function(method) {
var defaults = {
animSpeed : 'fast'
};
var option = {};
var methods = {
init: function(options) {
option = $.extend(defaults, options);
return this.each(function() {
code...
});
},
expand: function() {
return this.each(function() {
$(this).children('li').slideDown(option.animSpeed);
});
}
};
};
}(jQuery));
Upvotes: 1
Views: 638
Reputation: 219920
You should store the original options in the data
of the elements it is being called on:
return this.each(function() {
$(this).data('fname-options', options);
// Code...
});
so that you can later access it from your other methods:
expand: function() {
return this.each(function() {
var $this = $(this),
options = $this.data('fname-options');
$this.children('li').slideDown(options.animSpeed);
});
}
Upvotes: 4