Mornin' all.
I'm rewriting a prototype code to a JQuery plugin and don't know how to handle this piece :
this.observers = events.map(function(name) {
var handler = this["on" + name.].bind(this);
this.element.observe(name, handler);
return { name: name, handler: handler };
}.bind(this));
I ended up with :
this.observers = $.each(events , function(i, name) {
var handler = "on"+name;
$element.live({
name: handler
});
}
I'm totally wrong ? I don't understand well prototype bind() purpose.
Thanks for help !
EDIT: The context of that is a plugin init() function where I attach "dynamically" events and their handler coded as private methods...
plugin.init = function() {
// the plugin's final properties are the merged default and user-provided options (if any)
plugin.settings = $.extend({}, defaults, options);
if (!plugin.observers) {
var events = ("mouseover mouseout").split(" ");
plugin.observers = $.map(events, $.proxy(function(name) {
var handler = $.proxy(this['on' + name], this);
$element.bind(name, handler);
return { name: name, handler: handler };
}, this));
}
console.log(plugin.observers);
}
as for the Prototype-to-jQuery translation (read my above explanation on bind/proxy first), this should closely match the snippet above:
this.observers = $.map(events, $.proxy(function(name) {
var handler = $.proxy(this['on' + name], this);
this.element.bind(name, handler);
return { name: name, handler: handler };
}, this));
I'm assuming from the Prototype snippet that:
this
is a Prototype Class or a plain JS object that is the current context.this.element
is a reference to a DOM element, and in the jQuery case a jQuery-wrapped DOM element.onclick, onfocus
and similar possible callbacks are methods in the this
context.Without further context on how your code works or which piece of a Prototype plugin you are trying to rewrite this is as much as I can help you (which I hope is enough).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With