Reputation: 444
In my plugin I want to give full css controls. But some initial values has to be declared. To let users customize this initial values I'm calling a $.extend variable in which I pass all the inilial css.
As I try to override one or more part of that object, it will override EVERYTHING and not just what selected. Why?
I made I little fiddle here http://jsfiddle.net/Hfk79/ to be more clear:
Let's pretend this is my plugin:
$.fn.myPlugin = function( options ) {
var defaults = $.extend({
pCSS : {
color: 'red',
margin: '1em'
}
}, options );
var settings = $.extend( true, {}, defaults, options );
return this.click(function() {
$( this ).css( settings.pCSS );
});
}
Users can now override default options. And let's pretend I am an user who hate the red color and just want it to be blue and I feel OK with the other properties. I'd call the function passing this option:
$( document ).ready(function() {
$( '.plugin' ).myPlugin({
pCSS: {
color: 'blue'
}
});
});
HOWEVER this code will override EVERYTHING and not just the color!
Where am I doing wrong?
Upvotes: 2
Views: 2718
Reputation: 63524
Removing the first extend
and getting rid of the pCSS
inner object helps:
$.fn.myPlugin = function (options) {
var defaults = {
color: 'red',
margin: '1em'
};
var settings = $.extend(true, defaults, options);
return this.click(function () {
$(this).css(settings.pCSS);
});
}
$(document).ready(function () {
$('.plugin').myPlugin({
color: 'blue'
});
});
Upvotes: 2