Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assigning one property to another inside jQuery Object Literal

I’m refactoring existing working code in jQuery into jQuery plugin. In the original code, I have several variables which I use to store settings. One of which is referenced in the other:

var className = ".container";
var element   = `<div class="${className.slice(1)}"></div>`; 

In the plugin code I’m trying to do the same, but inside Object Literal and I’m getting undefined when I reference "className":

$.fn.pluginName = function (options) {

    var defaultSettings = {
        className: ".container",
        element:  function() {
            return `<div class="${this.className.slice(1)}"></div>`;
        };
    };

    var settings = $.extend({}, defaultSettings, options);
};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since you’ve said you don’t control how the element function is called, you can’t rely on this within it (unless you use bind, but there’s no need here).

I’m assuming options can override defaultSettings.className, so you don’t just want to use defaultSettings instead of this.

You can use settings, though:

$.fn.pluginName = function (options) {
    const defaultSettings = {
        className: ".container",
        element: () => {
            return `<div class="${settings.className.slice(1)}"></div>`;
        },
    };
    const settings = Object.assign({}, defaultSettings, options);
    // ...presumably more code here...
};

Even though it’s above const settings in the code, it won’t be called until after settings has been initialized with a value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading