I am new to Jquery plugins, I was searching a lot about widgets and plugins, however I am still not sure if this code is okay. Should I use widgets for stateful plugins? Or is this plugin correct? Does this code have any downsides? I was trying to make a container here, where you can add/remove elements.
(function($) {
// jQuery plugin definition
$.fn.container = function( options ) {
var defaults = {
width:'200',
height:'200',
elements: ['dadas', 'dasdasda','dasdasda'],
onAdd: function() {},
onRemove: function() {},
};
var options = $.extend( defaults, options );
this.add = function( item ) {
$newDiv.append( item );
options.elements.push( item );
console.log('The item in function add: ' + item);
options.onAdd.call( this, item );
};
this.remove = function( item ) {
this.options.onRemove.call( this, item );
};
var createNewElement = function( element ) {
return $('<div><span>' + element + '</span></div>');
}
var $newDiv = $( '<div></div>' );
return this.each(function() {
$newDiv.css( 'width', options.width );
$newDiv.css( 'height', options.height );
$newDiv.css( 'border', '1px solid Black' );
$(this).after( $newDiv );
$.each(options.elements, function( index, value ) {
$newDiv.append( createNewElement( value ) );
});
});
};
})(jQuery);
var $container = $( '#xxx' ).container({
width: '300',
height: '300',
onAdd: function( item ) {
console.log( item );
},
onRemove: function ( item ) {
}
});
$container.add('abcdefg');
<html>
<head>
</head>
<body>
<div id="xxx"></div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</html>