Skip to content

Instantly share code, notes, and snippets.

@julienrf
Created October 16, 2011 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julienrf/1291097 to your computer and use it in GitHub Desktop.
Save julienrf/1291097 to your computer and use it in GitHub Desktop.
Don’t use jQuery to write a web application
$next.attr('disabled', 'disabled');
$.each('.item-list-widget', function () {
var widget = this;
var next = $.find(widget, '.next'); // Use the jQuery API
next.disabled = true; // And use the native API on the result… Magic!
$.click($.find(widget, '.add-item'), function () {
var list = $.find(widget, 'ul');
$.append(list, $.create('<li>item</li>'));
if (list.childNodes.length >= 3) {
next.disabled = false;
}
});
});
// Find each widget in the dom and configure it
$('.item-list-widget').each(function () {
var $this = $(this);
// Handle click on the Add button
$this.find('.add-item').click(function () {
$this.find('ul').append('<li>item</li>'); // The way you’ll create the item may be more complex than that…
});
});
$('.item-list-widget').each(function () {
var $this = $(this);
var $next = $this.find('.next');
// At startup the 'next' button is disabled
$next.attr('disabled', 'disabled');
$this.find('.add-item').click(function () {
$this.find('ul').append('<li>item</li>');
// Enable the 'next' button if at least 3 items have been added
if ($this.find('ul li').length >= 3) {
$next.removeAttr('disabled');
}
});
});
<div class="item-list-widget">
<button class="add-item" type="button">Add</button>
<ul class="item-list"></ul>
</div>
<div class="item-list-widget">
<button class="add-item" type="button">Add</button>
<ul class="item-list"></ul>
<button class="next" type="button">Next</button>
</div>
// Find all widgets and setup their behavior
var ws = document.querySelectorAll('.item-list-widget');
for (var i = 0 ; i < ws.length ; i++) {
setup(Widget(ws[i]));
}
// Build an abstract representation of a list widget
function Widget(elt) {
return {
add: elt.querySelector('.add-item'),
next: elt.querySelector('.next'),
list: elt.querySelector('.item-list')
};
}
// The relevant code is in this function
function setup(widget) {
// At startup the 'next' button is disabled
widget.next.disabled = true;
// Handle click on the Add button
widget.add.onclick = function () {
var item = document.createElement('li');
item.textContent = 'item';
widget.list.appendChild(item);
// Enable the 'next' button if at least 3 items have been added
if (widget.list.childNodes.length >= 3) {
widget.next.disabled = false;
}
}
}
widget.next.disabled = true;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment