Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prototype code to jQuery ( bind(this) vs closures )

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);
}
like image 305
Jason Lince Avatar asked Nov 13 '22 22:11

Jason Lince


1 Answers

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).

like image 99
gonchuki Avatar answered Jan 09 '23 19:01

gonchuki