So, let's talk about how to build basic GUI applications. Before we proceed I'd like you to know the code below can be written in ~20 LoC in Knockout/Angular but I chose not to because that wouldn't really teach anyone anything.
So, let's talk about GUI.
It all boils down to two things.
- Presentation - this is your HTML, css and whatever the user directly interacts with.
- Data - this is your actual data and logic.
We want to separate them so that they can act independently. We want an actual representation of what the user sees in JavaScript object so it'll be maintainable, testable readable and so on and so on. See Separation of Concerns for more information.
Let's start with the data.
So, what does each thing have in your application?
- A First Item, either true or false
- A Sub Item either true or false, but never true if the First Item isn't true.
- A Second Item which is either true or false.
- A Number of Items which is a number
- Each of these items is an apple, banana or mango
The most intuitive thing is to start right there.
// our item, like we've just described it :)
function Thing(){ //we use this as an object constructor.
this.firstItem = false;
this.subItem = false;
this.secondItem = false;
this.numItems = 0;
this.items = []; // empty list of items
}
Well, that's a thing, we can now create them with new Thing()
and then set their properties, for example thing.firstItem = true
.
But we don't have a Thing
we have stuff. Stuff is just an (ordered) bunch of things. An ordered collection is commonly represented by an array in JavaScript, so we can have:
var stuff = []; // our list
var thing = new Thing(); // add a new item
stuff.push(thing); // add the thing we just created to our list
We can of course also communicate this to PHP when submitting. One alternative is submitting a JSON object and reading that in PHP (this is nice!), alternatively we can serialize it as form params (if you have any trouble with the methods in that question - let me know).
Now I just have a bunch of objects... and a headache.
Quite astute. So far you only have objects, you did not specify their behavior anywhere. We have our 'data' layer, but we don't have any presentation layer yet. We'll start by getting rid of all the IDs and add behavior in.
Enter templates!
Instead of cloning existing objects we'll want to have a 'cookie cutter' way to create the looks of new elements. For this we'll use a template. Let's start by extracting how your 'item list' looks into an HTML template. Basically, given your html it's something like:
<script type='text/template' data-template='item'>
<ul class="clonedSection">
<li style="list-style-type: none;">
<label><input class="main-item" type="checkbox" />First Item</label>
<ul class="sub-item" style="display: none;">
<li style="list-style-type: none;">
<label><input type="checkbox" />Sub Item</label>
</li>
</ul>
</li>
<li style="list-style-type: none;">
<label>
<input class="main-item" type="checkbox" />Second Item</label>
<ul class="sub-item" style='display: none;'>
<li style="list-style-type: none;">
How many items:
<select class="medium" required>
<option value="">---Select---</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</li>
<li style="list-style-type: none;"><div></div></li>
</ul>
</li>
</ul>
</script>
Now let's create a 'dumb' method for showing the template on the screen.
var template;
function renderItem(){
template = template || $("[data-template=item]").html();
var el = $("<div></div>").html(template);
return el; // a new element with the template
}
[Here's our first jsfiddle presentation demo](http://jsfiddle.net/RLRtv/, that just adds three items, without behavior to the screen. Read the code, see that you understand it and don't be afraid to ask about bits you don't understand :)
Binding them together
Next, we'll add some behavior in, when we create an item, we'll couple it to a Thing
. So we can do one way data binding (where changes in the view reflect in the model). We can implement the other direction of binding later if you're interested but it's not a part of the original question so for brevity let's skip it for now.
function addItem(){
var thing = new Thing(); // get the data
var el = renderItem(); // get the element
el. // WHOOPS? How do I find the things, you removed all the IDs!?!?
}
So, where are we stuck? We need to append behavior to our template but normal HTML templates do not have a hook for that so we have to do it manually. Let us begin by altering our template with 'data binding' properties.
<script type='text/template' data-template='item'>
<ul class="clonedSection">
<li style="list-style-type: none;">
<label>
<input class="main-item" data-bind = 'firstItme' type="checkbox" />First Item</label>
<ul class="sub-item" data-bind ='subItem' style="display: none;">
<li style="list-style-type: none;">
<label>
<input type="checkbox" />Sub Item</label>
</li>
</ul>
</li>
<li style="list-style-type: none;">
<label>
<input class="main-item" data-bind ='secondItem' type="checkbox" />Second Item</label>
<ul class="sub-item" style='display: none;'>
<li style="list-style-type: none;">How many items:
<select class="medium" data-bind ='numItems' required>
<option value="">---Select---</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</li>
<li style="list-style-type: none;">
<div data-bind ='items'>
</div>
</li>
</ul>
</li>
</ul>
</script>
See all the data-bind
attributes we added? Let's try selecting on those.
function addItem() {
var thing = new Thing(); // get the data
var el = renderItem(); // get the element
//wiring
el.find("[data-bind=firstItem]").change(function(e){
thing.firstItem = this.checked;
if(thing.firstItem){//show second item
el.find("[data-bind=subItem]").show(); //could be made faster by caching selectors
}else{
el.find("[data-bind=subItem]").hide();
}
});
el.find("[data-bind=subItem] :checkbox").change(function(e){
thing.subItem = this.checked;
});
return {el:el,thing:thing}
}
In this fiddle we've added properties to the first item and sub item and they already update the elements.
Let's proceed to do the same for the second attribute. It's pretty much more of the same, binding directly. On a side note there are several libraries that do this for you automatically - Knockout for example
Here is another fiddle with all the bindings set in, this concluded our presentation layer, our data layer and their binding.
var template;
function Thing() { //we use this as an object constructor.
this.firstItem = false;
this.subItem = false;
this.secondItem = false;
this.numItems = 0;
this.items = []; // empty list of items
}
function renderItem() {
template = template || $("[data-template=item]").html();
var el = $("<div></div>").html(template);
return el; // a new element with the template
}
function addItem() {
var thing = new Thing(); // get the data
var el = renderItem(); // get the element
el.find("[data-bind=firstItem]").change(function (e) {
thing.firstItem = this.checked;
if (thing.firstItem) { //show second item
el.find("[data-bind=subItem]").show(); //could be made faster by caching selectors
} else {
el.find("[data-bind=subItem]").hide();
}
});
el.find("[data-bind=subItem] :checkbox").change(function (e) {
thing.subItem = this.checked;
});
el.find("[data-bind=secondItem]").change(function (e) {
thing.secondItem = this.checked;
if (thing.secondItem) {
el.find("[data-bind=detailsView]").show();
} else {
el.find("[data-bind=detailsView]").hide();
}
});
var $selectItemTemplate = el.find("[data-bind=items]").html();
el.find("[data-bind=items]").empty();
el.find("[data-bind=numItems]").change(function (e) {
thing.numItems = +this.value;
console.log(thing.items);
if (thing.items.length < thing.numItems) {
for (var i = thing.items.length; i < thing.numItems; i++) {
thing.items.push("initial"); // nothing yet
}
}
thing.items.length = thing.numItems;
console.log(thing.items);
el.find("[data-bind=items]").empty(); // remove old items, rebind
thing.items.forEach(function(item,i){
var container = $("<div></div>").html($selectItemTemplate.replace("{number}",i+1));
var select = container.find("select");
select.change(function(e){
thing.items[i] = this.value;
});
select.val(item);
el.find("[data-bind=items]").append(container);
})
});
return {
el: el,
thing: thing
}
}
for (var i = 0; i < 3; i++) {
var item = addItem();
window.item = item;
$("body").append(item.el);
}
The buttons
The fun thing is, now that we're done with the tedious part, the buttons are a piece of cake.
Let's add the "add" button
<input type='button' value='add' data-action='add' />
and JavaScript:
var stuff = [];
$("[data-action='add']").click(function(e){
var item = addItem();
$("body").append(item.el);
stuff.push(item);
});
Boy, that was easy.
Ok, so remove should be pretty hard, right?
HTML:
<input type='button' value='remove' data-action='remove' />
JS:
$("[data-action='remove']").click(function(e){
var item = stuff.pop()
item.el.remove();
});
Ok, so that was pretty sweet. So how do we get our data? Let's create a button that shows all the items on the screen?
<input type='button' value='show' data-action='alertData' />
and JS
$("[data-action='alertData']").click(function(e){
var things = stuff.map(function(el){ return el.thing;});
alert(JSON.stringify(things));
});
Woah! We have an actual representation of our data in our model layer. We can do whatever we want with it, that's pretty sweet.
What if I want to submit it as a form? $.param
to the rescue.
<input type='button' value='formData' data-action='asFormData' />
And JS:
$("[data-action='asFormData']").click(function(e){
var things = stuff.map(function(el){ return el.thing;});
alert($.param({data:things}));
});
And while this format is not very nice it's something PHP (or any other popular technology) will gladly read on the server side.
So to wrap it up
- Separate presentation from data
- If you have JS logic - have a single source of truth - JavaScript objects
- Consider reading about it more, learn about common frameworks like KnockoutJS or AngularJS which have interesting less verbose solutions to this problem (at the cost of assumptions).
- Read more about UI architecture. This is a good (but hard for beginners) resource
- Avoid duplicate IDs, they're bad - while you're there don't store data in your dom.
- Don't be afraid to ask question - this is how you learn.
- You can pretty easily get rid of jQuery here.