I feel as if this is really simple and I'm having a "wood for the trees" moment, but that moment has lasted over a day now, so it's time to get help! I've Googled this and read lots of SO answers, but again, I'm having trouble applying the answers I've seen to my exact problem, no doubt due to my own shortcomings.
To illustrate the problem, I have this sample jQuery plugin (I tried to create a fiddle for this but don't know how to include a plugin external to the 'page' in a fiddle):
(function ($) {
$.fn.test = function (options) {
var settings = $.extend({
onItemClick: function () { },
itemArray: new Array(),
}, options);
for (i = 0; i < settings.itemArray.length; i++) {
var $item = $("<li></li>");
$item.html(settings.itemArray[i].itemLabel);
$item.click(function () {
settings.onItemClick.call(settings.itemArray[i]);
});
this.append($item);
}
return this;
};
}(jQuery));
As you can see, I'm accepting a function as a variable - onItemClick. I've left out the test that this exists and is a function for the sake of brevity.
My example page looks like this:
<body>
<div>
<ul id="testList"></ul>
</div>
</body>
</html>
<script type="text/javascript">
$(function () {
var testDataArray = new Array();
var itemLabel = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"];
var itemDate = ["2017-01-03", "2015-08-03", "2016-06-21", "2016-12-20", "2013-09-07"];
for (i = 0; i < itemDate.length; i++) {
var testData = {};
testData["itemLabel"] = itemLabel[i];
testData["itemDate"] = itemDate[i];
testDataArray[i] = testData;
};
$("#testList").test({
itemArray: testDataArray,
onItemClick: function (item) {
alert(item.itemLabel + ": " + item.item.Date);
}
});
})
</script>
So, when I call the plugin from my page, I want to be able to pass a function as a parameter and be able to include variables in that function which will be populated with real values by the plugin. That last point is where I'm getting stuck.
The code I've written doesn't work as is. Unsurprisingly, it throws the error
Cannot read property 'itemDate' of undefined
because settings.itemArray is not known within the scope of the function I'm trying to attach to the click event of the item. I understand that, I just don't understand what the correct way is to do this!