First thing we're going to do is modify our main.js to make it easier to access the todolist in our console (plus fix up an error from last post).
goog.provide('todomvc.main'); goog.require('mvc.Collection'); goog.require('todomvc.listcontrol'); todomvc.main = function() { var todolist = new mvc.Collection(); var todolistControl = new todomvc.listcontrol(todolist); todolistControl.createDom(); todolistControl.render(document.body); window['a'] = todolist; };
The only real change to the above is that I've added window['a']= todolist at the end. This will be removed later, but I like having easy access to specific variables in the console when I'm developing. This will allow me to call the todolist with just a.method.
Next up is the Control:
Whatgoog.provide('todomvc.listcontrol'); goog.require('mvc.Control'); todomvc.listcontrol = function(model) { goog.base(this, model); }; goog.inherits(todomvc.listcontrol, mvc.Control); todomvc.listcontrol.prototype.createDom = function() { this.el = goog.dom.htmlToDocumentFragment("<div>" + "<div>Todo</div>" + "<div><form><input type='text' /></form></div>" + "</div>"); console.log(this.el); this.setElementInternal(this.el); }; todomvc.listcontrol.prototype.enterDocument = function() { this.on('submit', function(e) { e.preventDefault(); e.stopPropagation(); var text = (this.getEls('input')[0]).value; this.getModel().newModel({'text': text}); return false; }); };
What this has done is add in the enterDocument function. Usually we should call goog.base() on this as well as it inherits from goog.ui.component and does some things we want to keep (like figuring out that it is attached to a document so child components will render). We put the setup in here because this is when we are first guaranteed that the DOM structure we create in createDom is in the document
From here I've call .on which is a method that we use for event handling. I've passed in the event to listen for and a function to handle it. There are other optional parameters I could pass such as a classname to only target one form and then a handler, but the function is automagically bound to the control and there is only one form so I don't need to.
The function stops the event and returns false to prevent the default submit, then it grabs the text from the first input under our control. I'm then getting the controls model and using the collection's newModel method which will put a new mvc.Model at the top and passing in the text and that's it.
try opening up the html file, typing something in to the field and pressing enter. You can then open up your javascript console and see the new model by entering in:
a.at(0); // returns your new model a.at(0).get('text'); // returns the text in your new model which should be what you typed in
Next post we'll create a new control for todos and have them display
No comments:
Post a Comment