简体   繁体   中英

jQuery plugin overwrite option

Unfortunately I am stumbling upon an issue with jQuery plugins. I made a small plugin to facilitate building bootstrap modals.

The options for the plugin look like this:

defaults = {
    modalName: "",
    size: "md",
    title: "",
    body: "",
    buttons: {
        confirm: {
            class: 'btn btn-primary',
            value: 'Save'
        },
        cancel: {
            class: 'btn btn-default',
            value: 'Cancel'
        }
    }
};

But I want the value of the confirm button to differ for some pages. I thought I could just do this:

$( 'body' ).CreateModel ( {
    // Different settings
    buttons: {
        confirm: {
            value: 'Save & exit'
        }
    }
});

But unfortunately, this completely purges the default object and it only leaves buttons.confirm.value . Is there any way I can fix this?

Thanks in advance!

You haven't shown us your implementation of how you're working with defaults and the object passed in arguments, respectively, but you would be able to solve this problem using $.extend .

Something like this:

$.fn.CreateModel = function(options) {
  options = $.extend({}, defaults, options);
  ....
};

Using the jQuery function .extend , You can pass true as first parameter that allow a deep merging .

You have to change the line this.options = $.extend( {}, defaults, options) ; to :

this.options = $.extend(true, {}, defaults, options) ;

See an example here : http://jsfiddle.net/n5BKk/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM