Java Reference
In-Depth Information
Next we'll create a
controller
object. This will be responsible for adding an event
listener to the form to see when the user adds information. When this happens, it will create
a new instance of the model and then render the updated view. Add the following code to
scripts.js:
js/scripts.js
(excerpt)
controller = {
watch: function(form) {
form.addEventListener("submit", function(event){
event.preventDefault(); // prevent the form from
being
↵
submitted
this.add(form.name.value);
}.bind(this), false); // binding this to the
controller instead
↵
of the form
},
add: function(name) {
var item = new Item(name);
view.render(item);
}
}
After this we create a view object with a
render()
method. This is used to produce an
HTML fragment that shows the instance's name (from the
name
property stored in the
model). It is dynamically inserted into the list using DOM API methods. Add the following
code to the scripts.js file:
js/scripts.js
(excerpt)
view = {
render: function(item) {
var list = document.getElementById("list");
var li = document.createElement("li");
li.textContent = item.name;
list.appendChild(li);
