简体   繁体   中英

Why function does not receive inputted JSON data?

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?

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

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

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