Reputation: 539
I just started writing Plugins for jQuery. I found a good tutorial how to start with it, but one point I missed. I want register a independent plugin-object for each element and I need them events.
Here the code I got atm:
(function($){
var MyPlugin = function(pElement, pOptions)
{
var element = $(pElement);
var object = pElement;
var settings = $.extend({
param: 'defaultValue'
}, pOptions || {});
this.onfocus = function() {
element.val('Focus');
};
this.onblur = function() {
element.val('Blur');
}
// DO I NEED THIS?
object.onfocus = this.onfocus;
object.onblur = this.onblur;
};
$.fn.myplugin = function(options)
{
return this.each(function()
{
var element = $(this);
if (element.data('myplugin')) { return };
var myplugin = new MyPlugin(this, options);
element.data('myplugin', myplugin);
});
};
})(jQuery);
Do I need to copy my public methods "onfocus" and "onblur" from "this" to "object"? Is there a better way?
Upvotes: 2
Views: 495
Reputation: 4948
The best guide for writing jQuery plugins is probably jQuery's own.
jQuery's event system is the best way of handling events for your plugin. If you're using jQuery 1.7+ (which I recommend, if it's possible), .on()
and .off()
are your workhorses. Not only can you bind browser events like focus and blur, you can create completely custom events like 'iamasuperstar' and trigger them manually with this.trigger( 'iamasuperstar' )
.
So you'd do something like this for your plugin:
element.on( 'focus', function() {} )
element.on( 'blur', function() {} )
...and whatever else you need.
Upvotes: 1
Reputation: 1943
Why not:
object.onfocus = function() {
element.val('Focus');
};
object.onblur = function() {
element.val('Blur');
}
Upvotes: 1