Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwriting settings when I write simple jquery plugin

Tags:

jquery

I try to write simple jquery plugin with some php code for displaying tables from database. Plugin allows user to search, go through the pages and sort. I know there's some great plugins for that, but I'm a newbie (6 months with any kind of programming) and I try to learn something.

Practically everything is done but I stopped at trying to do "multilevel" options.

The simplest option for user looks like that (almost all of them looks like that):

$('#main').ableTable({
    mode :'sqlite'
})  

Then it overrides the default settings:

var settings = $.extend({
    mode : 'mysql' 
} ,options);

That's simple.

But If I have some more complicated option like:

var settings = $.extend({
    translate :{
        navigation :{
            prev :'previous' ,
            next :'next'
        } ,
        search :'search' ,
        no_result :'nothing was found' ,
        from :'from' ,
        total :'total'
    }
    // other options
} ,options);

Then if user declare only:

$('#main').ableTable({
    translate :{
        navigation :{
            prev :'poprzedni'
        }
    }
})  

It overwrites everything in settings.translate

How to correclty handle user defined options, if I wanna overwrite only the settings.navigation.prev (in this example) and leave the rest of default setttings?

like image 523
Dariusz Majchrzak Avatar asked Dec 25 '22 14:12

Dariusz Majchrzak


1 Answers

You need to use the deep parameter in the overloaded extend() function - it's basically another version of the same function, but it makes it recursive so it looks within the object, rather than just the top level...

var settings = {
    translate :{
        navigation :{
            prev :'previous' ,
            next :'next'
        } ,
        search :'search' ,
        no_result :'nothing was found' ,
        from :'from' ,
        total :'total'
    }
}

var options = {
    translate: {
        navigation: {
            prev: "something else"
        }
    }
};

$.extend(true, settings, options);

Have a look at the documentation for extend() to find out more...

https://api.jquery.com/jquery.extend/

like image 79
Reinstate Monica Cellio Avatar answered Jan 04 '23 23:01

Reinstate Monica Cellio