Cat Clicker HTML and Bindings – JavaScript Design Patterns

Cat Clicker HTML and Bindings – JavaScript Design Patterns


Let’s keep working together and wire up the view. Now previously, when we were doing model view octopus, the octopus was grabbing on to these elements by their ids and then updating them whenever view.render got called. Now, Knockout doesn’t actually need these elements to have ids. It just need us to put data bindings on them. Now, the very first thing I’m going to do is remove the ids. Removing the ids is not necessary, but I’m taking them away just for clarity. In a real situation, I might have a class on each of these describing what they do. That way, our CSS can hook onto it and style it and make it look pretty. So now, our h2, div, and image all have data-bind attributes here. First, let’s talk about the h2. We want the h2 to be wired up with the name of the cat. In fact, more specifically, we want the text of the h2 to be whatever the name of the cat is. Knockout’s binding for this is text: name. Whatever the name property is on the view model over in our JavaScript file, that’s what the text of this h2 gets set to. And in fact, if we hop back over to our app, we can see there is the name right there. Its initial value should be Tabby. If I save my work and I hop back over here and refresh, we should see the name update with Tabby. Let’s hop back to our HTML. This div here is going to be very similar. The text inside of the div is going to be a click count. Now, the image itself is going to be a little bit different. First of all, we know that when we click, we want increment counter to run. We also want the source attribute of this image to update as the source changes. In this simple example, it won’t change, but we still want to use Knockout’s binding system to do this. To put multiple bindings inside of a data-bind, just use a comma. The way you bind an attribute inside of Knockout is with the binding attr colon, and then an object literal here with source to whatever you want to bind it to. In this case, in app.js, it’s called image source. If the image source observable were ever to change, then the attribute, source, on this image would change. Let’s save this and go back to our browser and see if it works. Sure enough, the image pops up, and when you click, the number increments. Pretty cool. Now, once again, these bindings are the things that are connecting up the view and the model, and Knockout is handling all of the logic to make that synchronization happen.

Leave a Reply

Your email address will not be published. Required fields are marked *