KnockoutJS is a dynamic UI framework that can really liberate you from the tedium of low-level DOM manipulations. Even though I’ve only played with it for a little while, I’ve become a huge fan. One of my initial attempts is to create an animated text input similar to Twitter’s.
The UI is quite simple. The textbox should display a “placeholder” prompt. When the user clicks inside the textbox, expand it and display a save button, initially disabled. If the user types something (other than white space), enable the button. If the textbox loses focus, shrink it to its original size, unless it contains a valid comment.
To show the placeholder prompt, I could use the HTML5 “placeholder” attribute. Unfortunately this isn’t supported by all browsers (what else but IE 9 and below). So I’m using a div to wrap the textbox and display the prompt as an overlay.
The view model’s isEditing boolean observable reflects whether the textbox has focus. It’s wired to the hasfocus binding on the textbox. Additionally, clicking anywhere on the wrapper div should activate the observable, since the user should be able to focus by clicking on the overlaying prompt.
The content of the textbox is tied to the newComment observable. Per the valueUpdate binding, it is updated after a key press. Additionally, the propertychange and input parameters allow it to be updated when the user copies and pastes with the mouse or keyboard.
To animate the textbox, I use a custom binding which is also wired to the isEditing observable. The animation should be performed only when the textbox is empty or contains only white space. When the textbox has focus, it’s expanded. When it loses focus, it’s collapsed.
The button is shown when the textbox has focus. Additionally it’s only enabled when the user enters non-white space text. Clicking on the button simply adds adds the new comment to the comments observable array and clears the textbox. The beauty is that KnockoutJS automatically updates the UI to reflect the change.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48