this - Calling jQuery's ready() with plugin context -
my plugin allows specify callback in options. plugin may run before dom ready, need make sure callback runs once dom ready, i'm wrapping callback.call()
within $( document ).ready()
handler.
the problem want maintain plugin's context within callback. in other words, within callback, want this
plugin, not document
.
this i've come with, i'm not sure it's best way.
function myplugin( element, options ){ this.element = element; this.options = $.extend( {}, defaults, options ); myplugin.prototype = { functionwithcallback: function(){ if ( typeof this.options.callback == 'function' ) $( document ).ready( function( plugin ){ plugin.options.callback.call( plugin ) }( ) } } }
that last line ugly, allows me pass plugin's this
context callback.
i rather $( document ).ready( this.options.callback )
, done it, within callback, this
document
doesn't help, , doesn't give me easy access element plugin called on...
is there better way?
function.prototype.call
solid solution sort of situation.
calling functions different context of this
part of it's for.
if you'd more elegant es5 solution (so newer browsers only) can use .bind
$(document).ready(plugin.options.callback.bind(plugin));
bind sets function's this
value when call (as other parameters optionally). here's an example of how .bind
works.
jquery shims $.proxy
if you'd use that.
you can
$(plugin.options.callback.bind(plugin));
Comments
Post a Comment