-2
\$\begingroup\$

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>

\$\endgroup\$
1
  • 6
    \$\begingroup\$ Welcome to Code Review! This is just a dump of code, which makes this question very unclear, and bordering off-topic. Please see how to ask a good question \$\endgroup\$
    – Heslacher
    Dec 16, 2016 at 10:31

1 Answer 1

1
\$\begingroup\$

So two suggestions:

I would move the declaration var $newDiv = $( '<div></div>' ); to be above the this.add = function... declaration. It is a small readability thing since the function defined uses $newDiv and when I ran across it I had to go hunt down it's assignment to make sure it wasn't referencing an undeclared variable.

Also in your "remove" function you are not removing items from the "options.elements" collection or the DOM. So essentially your code only allows for the addition of items to your state stores but never their removal.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.