For the past couple of weeks I have been working on some pages using knockout.js that have a fairly complicated UI. A few of the elements in the pages don't look or function like standard HTML elements and there are a lot of lists that could contain lists (essentially a tree). While I would have loved to use angular for this, I ended up going with Knockout mainly due to there being a lot more familiarity with that framework throughout Sonoma (myself included) and there was a short turnaround time.
I put together a quick demo of some things that I thought were interesting on this JS Fiddle.
To create a tree like structure, I defined a JS constructor function Node that will act as typical tree node containing a Label and a list of children nodes. I created a function on the Node to add a child to make view cleaner and I had my objects defined. I applied bindings to the "root" node and I had a pretty standard data tree.
In my HTML view I created a "template" for each node so whenever a new node was created I automatically use that template. In each template I needed to expose 2 actions. The first one is a button that would add a child Node to the current Node. That button just calls the prototype function that was defined previously. The second button is to remove the current Node from the ObservableArray that it is currently in. To do that I knew that the parent scope would be the parent node (a new scope is created for each template), and that I could remove it from the collection using the Remove method on the array. Finally I put a check on there to make sure that the $parent isn't equal to the $root so the root node never gets removed.
For the buttons I ended up changing their styles to look dramatically different. For the delete buttons I just wanted them to display as a "X" icon so I changed the background of the button to the image, removed the border and changed the cursor to a pointer to make it more obvious. The other thing I had to do was to remove the focus outline of the button. To do that I added an :active pseudo selector to remove the outline that is added.
For the Add buttons I wanted to display text as well as an image so I needed to do a little more work. First, I added an underline to the text and changed the color to make it more apparent that this was clickable. I then applied the same styles ass the delete button except for the background image. For the image I added a a ::before selector to put an image before the button. Now those images will be displayed with the button and are clickable just as if they were part of the button itself. I also don't have to remember to add that image if I need to add a similar looking button elsewhere in my application, which would be pretty likely.
No comments:
Post a Comment