Trying to learn extendable jQuery plugin development. I'm completely stumped on how to call functions within a class from the jQuery plugin wrapper.
I created the wrapper for my code mostly from here , and have tried to understand/use this but haven't had much luck.
The important bits of the code below. I'd like it so I can call (eg) $(something).carousel(5)
and it passes that number to the slide
function within the Carousel class. Same for strings, so $(something).carousel('go')
would run go
within the Class.
How can I do this with this structure?
(function(window, $){
var Carousel = function(elem, options){
this.elem = elem;
this.$elem = $(elem);
this.options = options;
};
Carousel.prototype = {
defaults: {
[...]
},
init: function() {
this.config = $.extend({}, this.defaults, this.options);
this.create();
return this;
},
create: function() {
[...]
},
slide: function(num) {
[...]
}
};
Carousel.defaults = Carousel.prototype.defaults;
$.fn.carousel = function(options) {
return this.each(function() {
var carousel = new Carousel(this, options);
if (!options || typeof options == 'object') carousel.init();
else if (typeof options == 'number') carousel.slide(options);
else if (typeof options == 'string') carousel.options;
});
};
window.Carousel = Carousel;
})(window, jQuery);
You're more or less on the right track, your main problem is that calling carousel.options
will just access the options
attribute of your Carousel
instance. What you want to do is dynamically call the function on the instance:
$.fn.carousel = function(options) {
return this.each(function() {
var carousel = new Carousel(this, options);
// do a loose comparison with null instead of !options; !0 == true
if (options != null || typeof options === 'object')
carousel.init();
else if (typeof options === 'number')
carousel.slide(options);
// make sure options is the name of a function on carousel
else if (typeof options === 'string' && typeof carousel[options] === 'function') {
carousel[options](); // call the function by name
}
});
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.