I’m writing a simple jQuery plugin that will interface with a JSON object/array. I want to make that object array flexible enough so that people can pass their own to the plugin function. I’d like the user to be able to notify the plugin of how to get to two different values in the JSON object. For instance, let’s say this is the JSON —
[
{
name: "Baseball Opening Day",
format: "jpg",
urls: {
small: "http://myurl.com/images/small/baseball.jpg",
big: "http://myurl.com/images/big/baseball.jpg"
}
},
// etc.
]
If the plugin “knows” it will be passed an array of image objects, but that those image objects might be formatted in a number of ways, how can we pass an option to tell it where to find various things? For example, if I want to display a caption, I will ask for a reference to the caption value. This one is fairly easy:
$("gallery").myPlugin({
references: {
caption: "name"
}
});
Inside the plugin, we can get to the value like this, once we are looping through the gathered image objects:
// Assuming the value passed in is called "options"...
var caption = image[options.references.caption];
That will be interpreted as image[“name”] which is identical to image.name and works fine.
But how do you tell the plugin how to get to image.urls.small? You can’t do this:
$("gallery").myPlugin({
references: {
caption: "name",
urlSmall: "urls.small"
}
});
because it would be interpreted as image[“urls.small”] and return undefined.
Is there a way to pass this? Or at that point do I have to use a callback function like so:
$("gallery").myPlugin({
references: {
caption: "name",
urlSmall: function () {
return this.urls.small;
}
}
});
// Call it like this inside the plugin image loop
var urlSmall = options.references.urlSmall.call( image );
I know that is an option, but I’m wondering if there is a way to avoid forcing the user to write a callback function if they can pass a reference to the nested object property instead, somehow?
Thanks!
You just need a method that can split those property names. Here’s something to get you started.
Inside your plugin, you can use
Lodash’s
_.getproperly handles all corner cases as do other utility libraries.