Skip to content

Instantly share code, notes, and snippets.

@ethyde
Created September 30, 2014 15:05
Show Gist options
  • Save ethyde/ea8506513ed93d318579 to your computer and use it in GitHub Desktop.
Save ethyde/ea8506513ed93d318579 to your computer and use it in GitHub Desktop.
// Use $.extend() to copy existing functionality
var demobox = $('#' + id);
demobox.empty();
var forms = {};
forms.enquiry = {
email: 'enquiries@domain.com',
sendForm: function () {
//code which sends email
demobox.append('sending email to: ' + this.email + '...' + '<br>');
}
};
forms.contact = {
email: 'contact@domain.com'
};
forms.feedback = {
email: 'feedback@domain.com'
};
//Create a new object and copy the sendForm function from forms.enquiry to forms.contact and forms.feedback
forms.contact = $.extend({}, forms.enquiry, forms.contact);
forms.feedback = $.extend({}, forms.enquiry, forms.feedback);
forms.enquiry.sendForm();
forms.contact.sendForm();
forms.feedback.sendForm();
// Reset
$('#' + id).empty().hide();
// Result HTML
// sending email to: enquiries@domain.com...
// sending email to: contact@domain.com...
// sending email to: feedback@domain.com...
// Use $.extend() to specify custom settings for a plugin
$.fn.helloWorld = function (options) {
// specify the default options for the plugin
// Establish our default settings
var settings = $.extend({
text : 'Hello, World!',
color : null,
fontStyle : null
}, options);
// Remember that within the plugin, this refers to the jQuery instance, and not the element, so we don’t need the wrapping $().
// n'est pas forcément each(), mais une collection jQuery tel que bind()
// http://remysharp.com/2010/06/03/signs-of-a-poorly-written-jquery-plugin/
return this.each( function() {
// ici $(this) est H2
$(this).text( settings.text );
if ( settings.color ) {
$(this).css( 'color', settings.color );
}
if ( settings.fontStyle ) {
$(this).css( 'font-style', settings.fontStyle );
}
});
};
$('h2').helloWorld({
text : 'Salut, le monde!',
color : '#005dff',
fontStyle : 'italic'
});
// With callback
$.fn.helloWorld = function (options) {
// specify the default options for the plugin
// Establish our default settings
var settings = $.extend({
text : 'Hello, World!',
color : null,
fontStyle : null,
complete : null
}, options);
return this.each( function() {
$(this).text( settings.text );
if ( settings.color ) {
$(this).css( 'color', settings.color );
}
if ( settings.fontStyle ) {
$(this).css( 'font-style', settings.fontStyle );
}
// appele la function en callback s'il y en a une de définie
if ( $.isFunction( settings.complete ) ) {
settings.complete.call( this );
}
});
};
$('h2').helloWorld({
text : 'Salut, le monde!',
color : '#005dff',
fontStyle : 'italic',
complete : function() { alert( 'Done!' ) }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment