javascript - Add function to prototype of $(this) -
i'm extending jquery.contentcarousel plugin, , i've reached specific point i'm defining new functions via __prototype__
. shrunk code down demonstrate essential part:
(function($) { var aux = { navigate : function(){ //... }, } methods = { init : function( options ) { return this.each(function() { var $el = $(this); //this slippery line: $el.__proto__.scrolloneleft = function() { aux.navigate( -1, $el, $wrapper, $.extend(settings, {sliderspeed: 10, slidereasing: ''}), cache ); }; }); } } $.fn.contentcarousel = function(method) { if ( methods[method] ) { return methods[method].apply( this, array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'method ' + method + ' not exist on jquery.contentcarousel' ); } }; })(jquery);
this works on modern browsers, problem $el.__proto__
not working in ie9 , ie10 (yet). i'm not jquery ninja, guess isn't proper solution anyway.
so question is, how define new method in scenario?
yes not proper way of doing this. jquery has great extensibility capability, , case covered in cross-browser way.
you can define new functions on jquery array object, by:
jquery.fn.asdfize = function () { this.html('asdf'); return this; // chainability }
you can use $('div').asdfize();
replace div's innerhtml asdf
.
this need, $(this)
has jquery array object (jquery.fn
) it's prototype.
the old jquery wiki has nice article plugin authoring covers this.
edit:
you have done in code $.fn.contentcarousel
. how other case different?
edit2:
in part of code:
return this.each(function() { var $el = $(this); $el.__proto__.scrolloneleft = function() { ... }; });
you overwrite scrolloneleft
function in every iteration of each. it's not want!
you might want define function once instead, use this
inside jquery object call on.
Comments
Post a Comment