0

I've got a custom jQuery plugin I'm working on with a bit of issue with JSON.

I'm using the jQuery plugin boilerplate to create this and am setting the default properties at the top like so:

// Create the defaults once
var pluginName = "customHighlight",
        defaults = {
            actions: [{"test_action":"Test action"}],
            position: "left"
};

The issue is that when I try to set my own properties on initiation of the plugin like so:

$('div,p').customHighlight({
     actions: [{"1_action":"1 action"}]
});

I get nothing coming through. Am I making a school boy error that I haven't caught here?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Tapha
  • 1,491
  • 3
  • 17
  • 32

2 Answers2

0

It's not quite clear what you mean by "nothing coming through". It's entirely possible that you're making a mistake in your implementation of the boilerplate, and you haven't shown any of the relevant code, so we can't point that out for you, but there is one general design flaw in your setup.

If you're using the boilerplate correctly, your plugin's settings property will look like this:

{
    actions: [{"1_action":"1 action"}],
    position: "left"
}

I assume you were expecting actions to be an array with two objects. This outcome is because you are specifying a value for actions, and so $.extend which is being used in Plugin.prototype.init doesn't use the default value.

You could solve this by changing this line in init:

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

To this:

this.settings = $.extend( true, {}, defaults, options );
                      //  ^ "deep" param

Setting deep indicates that $.extend should be applied recursively. But this doesn't work for arrays, so you also need to make sure actions is an object:

var pluginName = "customHighlight",
        defaults = {
            actions: {"test_action":"Test action"},
            position: "left"
};

Now, calling customHighlight like this:

$('div,p').customHighlight({
     actions: {"1_action":"1 action"}
});

Would result in a settings object that looks like this:

{
    actions: {
       "test_action": "Test action"
       "1_action": "1 action"
    },
    position: "left"
}

Fiddle

David Hedlund
  • 128,221
  • 31
  • 203
  • 222
  • Thank you for taking the time to answer this. Luckily I realised my error was just in not really knowing how jQuery boilerplate really works! I've typed my answer/thought-process below. – Tapha Dec 21 '15 at 10:11
  • @Tapha: Glad your issue is solved. You may still want to note that the `actions` array will be overwritten and not appended to, unless you manually intervene to change that. – David Hedlund Dec 21 '15 at 10:24
0

I realised that the settings object is what I needed to retrieve, instead of the defaults object that I was retrieving in my code. I didn't provide enough info here for a successful answer to be given so apologies. But the issue is now resolved.

Cheers

Tapha
  • 1,491
  • 3
  • 17
  • 32