Reputation: 101
I want to override a init function of a jquery plugin & also a custom function (html, in example) of the plugin. But nothing is working. Here is my code
Thanks in advance.
(function(jQuery) {
jQuery.mainplugin = function(element, options) {
var defaults = {};
this.init = function() {
this.settings = jQuery.extend({}, defaults, options);
alert('main')
// more code here
};
this.html = function() {
// main code here
}
this.init();
};
jQuery.fn.mainplugin = function(options) {
return this.each(function() {
if (undefined == jQuery(this).data('mainplugin')) {
var plugin = new jQuery.mainplugin(this, options);
jQuery(this).data('mainplugin', plugin);
}
});
};
})(jQuery);
Here is my code for override:
$(document).ready(function($) {
$.fn.mainplugin.init = function() {
alert('override')
}
$.fn.mainplugin.html = function() {
alert('override')
}
$(".is-wrapper").mainplugin();
});
Upvotes: 1
Views: 522
Reputation: 337560
Instead of 'overriding' the functions, pass them in to the plugin via the options
object:
(function($) {
$.mainplugin = function(element, options) {
var settings = $.extend({
init: null,
html: null
}, options);
this.init = settings.init || function() {
console.log('main')
};
this.html = settings.html || function() {
console.log('html');
}
this.init();
};
$.fn.mainplugin = function(options) {
return this.each(function() {
if (undefined == $(this).data('mainplugin')) {
var plugin = new $.mainplugin(this, options);
$(this).data('mainplugin', plugin);
}
});
};
})(jQuery);
$(document).ready(function($) {
// plain
$('.foo').mainplugin().data('mainplugin').html();
// overridden
$(".is-wrapper").mainplugin({
init: function() {
console.log('init override');
},
html: function() {
console.log('html override');
}
}).data('mainplugin').html();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo"></div>
<div class="is-wrapper"></div>
Upvotes: 1