开发者

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(t开发者_运维知识库his));

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜