Reputation: 618
I'm trying to write my first jquery plugin but I'm running into some difficulties.
Code snippets:
Here I am initializing my plugin and setting the function that should execute when MyEvent occurs.
$("#myMap").MyPlugin({ myEvent: function() { alert("test"); } });
And this is the function in my plugin script
function setEvents(options) {
$.each(options, function(event, fn) {
if (typeof (fn) == 'function') {
if (event == "myEvent") {
$(myDiv).click(fn);
}
}
});
}
This works fine, but I want to retrieve information from the plugin while the even occurs. Basically I want to receive a parameter I have set in that "setEvents" function.
$("#myMap").MyPlugin({ myEvent: function(myParam) { alert(param); } });
I cant seem to figure this one out, can someone point me in the right direction.
UPDATE: a more complete snippet of my current plugin script
(function($) {
var defaults = {
width: 300,
height: 300,
myEvent: null
};
$.fn.myPlugin = function(options) {
var options = $.extend(defaults, options);
var myDiv = $(this);
return this.each(function() {
setEvents(options);
});
})(jQuery);
Upvotes: 1
Views: 613
Reputation: 262919
Since the myEvent
event is mapped to a click
event by your plugin, you can pass a parameter map to click() in order for it to be ultimately passed to your handler:
if (typeof(fn) == "function") {
if (event == "myEvent") {
$(myDiv).click({
param: myParam
}, fn);
}
}
Then you can write:
$("#myMap").MyPlugin({
myEvent: function(event) {
alert(event.data.param);
}
});
Upvotes: 2