JS Legos: Reusable UI Patterns in JavaScript – Tyler Benziger

all right really excited to be here let’s go ahead and get started the talk isn’t gonna talk about reusable UI components in JavaScript so real quick before we dive in just a brief intro I’m Tyler you can find me on the net under ty Ben’s github twitter you guys want to email me I actually have to get on a plane as soon as I’m done here so I won’t be able to stick around for too long so if you guys have any questions that don’t get answered feel free to give me a shout out on any one of those places and if you hate my slides they are in them and they’re kind of ugly there’s a web-based slide deck at the link on the right so my blog ty bends comm I posted a link at the top and there on the conference site as well if you want to follow along with prettier slides so I work at Adobe I was hired on as an intern and the team I was hired into you was contributing to jQuery Mobile at the time so I got some background with jQuery and kind of my crash course in JavaScript was writing theme roller for jQuery Mobile which was a lot of fun shortly after that project was done my team kind of transitioned out of jQuery Mobile in general and we were kind of repurposed so our new purpose is to kind of kickstart and prototype out these newer product ideas where this kind of smaller R&D team so we meet with customers and do agile developments lots of fun but when we started the whole thing we knew that we were going to need to implement some really common UI stuff from project to project so we stopped and we kind of wrote this reusable JavaScript framework it’s just this UI component framework and we call it web Pro and through kind of interacting with this framework and understanding the concepts under it I kind of got really into this idea and so I thought I’d come give a talk about it so we’re gonna talk a little bit about what writing code this way entails so what we’re gonna cover will go through three different sections I’ll highlight we’ll walk through some examples of different UI patterns talk about how understanding the UI itself the visuals can shed some light on how to organize your code and then I’ll get preachy for a second about decoupling your markup your CSS and your JavaScript and then at the end we’ll hone in kind of on the JavaScript components themselves and some of the requirements around writing truly flexible and use reusable JavaScript so UI patterns this stuff’s fun I find that it’s a lot easier to show than to tell so we’re just gonna walk through a few examples here and I’m just gonna throw some UI components on the screen and we’re gonna talk about how we would implement these things at a high level we’re not gonna do any coding at this point so just talk about what we would need to kind of make the thing that we see on the screen so we see this slider and we want to implement this thing in the web so we need some HTML there’s two elements right we have the thing that’s moving that I call the thumb and the thing that’s moving inside I called the track so the whole point of a slider is that I can have the user drag this little thumb around and then the position of the thumb relative to the track maps to some arbitrary value right and I can hook a slider to mean something more significant than just what we see here so we could we could write a slider we could just have a couple HTML elements some CSS and write all the JavaScript we need to kind of drag this thing around and map the position to a value and that’s fine but it’s helpful if you kind of stop and assess what sort of underlying behaviors are being implemented in a component like this and are there any useful abstractions that we can make if we’re gonna roll one of these components ourselves so in this case the actual behavior of clicking and dragging something is a really common pattern in many UI components and actually jQuery UI has a widget called the draggable which is this exact pattern so it’s just the chunk of code you pass in HTML element it sets up all the events that would constitute a drag so you Mouse down you move the mouse you mouse up and it makes it make sure that the the element follows the mouse wherever it goes so you get this dragging thing so that’s its own isolated component we could stop and we can write our own little draggable and then we could create a slider using that draggable so here’s what the legos thing comes in because we’re making these useful abstractions and we kind of end up with these smaller components that can be used as building blocks to make cooler things so there’s actually one more abstraction that we made in our little UI framework that we call a drag tracker and so what it comes from is you think about a draggable itself and that behavior of the item following or sorry the element following the mouse wherever it goes during a drag it’s not necessarily always what you want it is a common pattern but what we did is we wrote this little component called the drag tracker which sets up all the same of that constitute a drag but instead of being forced to have the the item move wherever the mouse goes it just reports these updates basically on what the mouse is doing so callbacks or it submitting events with some data so that you can just be updated on what the mouse is doing so it’s very behavior agnostic right it’s just a little component it gives you some mouse data

during a drag and so you can use it for lots of stuff I just wanted to show a quick example of a little component I read so this is a numeric spinner and I you know wrote this thing really quick it does all the normal numeric spinner stuff I can increment and decrement the number with the arrow keys or I can click these buttons or I can press and hold all that stuff one little hidden feature is that if you start a drag on either of the buttons and go upward or downward you get the value changing so now my Y change and in my mouse position is mapped to this integer right so it’s kind of this hidden invisible slider feature granted not the most discoverable UI but it is a valid pattern and actually some of the Adobe apps have that sort of hidden feature I can’t remember which ones off the top of my head so again understanding thinking of abstraction ahead of time and understanding these patterns can be helpful so we can actually write a drag tracker first and you can implement a draggable using that drag tracker right now every time it’s reporting what the mouse is doing during the drag we can just say move the HTML element where it goes and now we have a draggable then we can implement our slider using the draggable so we’re building up as we go all right let’s try another one this is a color picker pretty easy we were gonna implement this thing let’s focus on the two elements that are on the left so we have the rainbow looking thing that can we implement it as a slider right in this case it’s vertical so hopefully when we wrote our slider we thought far enough in advance to allow for that use case so now we’re just mapping the Y position of this little thumb to the hue for this color now the thing on the left is a bit different it’s kind of the square and we’re dragging around this circle and the X and the y value of where the circle are relative to the box actually mapped to saturation and lightness so we could write a little widget that does the draggable thing but it’s actually just another example of a draggable whose position maps to a value so to me this is still a slider it’s actually two dimensional sliders so what I did is I went back into my slider and I hacked it to be able to take either a horizontal slider or vertical or both so now we can have a two dimensional slider and then I can take the x and y values map them to saturation lightness and I’ve got the whole thing so my whole color picker was just two sliders and I had to augment my my basic slider component but I’m pretty much done so it’s these discrete smaller components all right let’s do this one this one’s kind of fun so this is a navigation thing that I stole from Khan I think they were showing off like the speed of their NAB here we’re just going to talk about the underlying state toggling stuff that’s going on here so let me stop that for a sec so let’s define this first I call this component tabs some people get kind of picky about tabs like they have to have the links on top and you have to click on them in this case they’re on the left and you’re using hover to activate them shouldn’t matter right so the whole idea of tabs is I have a set of links and map to a set of panels and when I activate one of these tabs it’s the only one active and it has a matching panel that gets activated as well so if we’re gonna implement tabs there’s a couple ways you can do it what I’m gonna talk about is it’s kind of an unconventional way so what we did in web Pro is we decided to split tabs and panels into their own different components and that sounds weird and I’ll get to why it’s cool in a second so let’s just think of tabs by themselves if we want to implement a widget that just handled the tab so what’s the behavior that we need to implement we have a set of links and only one of them can be active at a time to us that sounded pretty familiar if you’ve been around the web with form controls there’s something called a radio button very similar behavior right I’ve got this set of options only one can be active at a time so we took that name and that underlying behavior and we created this base class that handles that that basic logic so we call this thing a radio group and the whole point of a radio group is it’s just a collection of things and only one thing can be active at a time then we took our tabs and we actually derive it from that that base class and then when we want to go look at panels by themselves you notice it’s the same basic behavior there’s there’s a set of panels here there’s five panels you only see one at a time because only one is active so the inactive state for the panels and the inactive state for the tabs look really different right you can always see inactive tabs you can’t see inactive panels that’s a CSS thing too as far as toggling state goes it’s the same underlying behavior I have a set of panels and I’m only going to activate one at a time so my tabs and my panels both derive from the same base class which is our radio group and then we’re able to add a little extra stuff to it to be able to link the two right so now every time I activate one of my tabs it’s got a matching panel and it can emit a notification or activate a specific panel that matches it so I’ve got these things decoupled so again it sounds weird to split up tabs and panels the biggest reason why we do it is because we’ve gotten into situations before we have a comp come to us and we realize that they’re just toggling a lot of states a lot of fancy tab stuff but you might actually need two different sets of panels to be driven by one set of tabs so you have this flexibility where I’ve got you know these tabs up here on the page I’ve got a panel that’s being toggled down here and then a panel

way over here but the the tabs are driving all of that so when you decoupled those you can do more flexible things so that’s tab so one other thing I like to talk about with tabs is different names for the same thing so all of these examples on this page are actually being driven by the same exact component so we have our traditional tabs on the Left accordions though the mark-up is arranged a little differently in there there’s a lot of like animation stuff going on it’s the same thing I have a set of links that map to a set of panels and I’m only activating one at a time slideshow is actually the same thing so that if this was you know these should be images they’re just numbers now but the idea is that I’ve got thumbnails on the left-hand side am I actually slide on the right and whenever I activate my thumb I get the matching slide and then it–and you know I’ve got some extra stuff for my slideshow component that allows me to auto play and iterate through my tip and my thumbnails or the tabs so there’s a little thing to kind of open your eyes when you think of these components cuz a lot of UI frameworks actually implement these things in different ways and you end up writing a lot of the same code because you’re managing some of these base level behaviors like our radio group so all of this is cool and the whole point of coming to understand these competitors is one making these useful abstractions and two not running for the door when your designer send you a comp like this so this is something I just found on dribble it’s this funky new UI and you see something this is a front-end developer and you kind of think holy crap what am I gonna do with this so first thing you do is you take a deep breath and then you remember your UI patterns so if we think about first we got to get the HTML and CSS out of the way for this thing which admittedly is the hardest part but then when we talk about the JavaScript that’s driving this behavior and the state toggling stuff it’s actually all stuff that we have together already so the these eight icons are arrayed around this circle and I can activate one of them I think he meant it to be a touch experience we can think of it as just now so might be a little bit of JavaScript to say when the mouse hovers over one of these things move this little blue selector and then you can click on one of them to activate it so activating one of them just toggle some state in other places on the on the page right so when I activate that volume I get a different state in the middle of the circle when I activate the Wi-Fi same thing so I can actually think of these eight icons as tabs I can think of a set of panels being in the middle of my circle there and now I’ve just got a one to one relationship and I had tabs and panels in addition there’s some state being changed around the circle and we can think of those additional elements as living inside their own separate set of panels so now we again this is an example of one set of tabs two sets of panels we have a set of panels in the middle of circle I’m gonna set up panels that gets overlaid on top of the circle and then you need some stuff to you know handle the buttons sliding out which is probably just CSS and then something like this this volume slider here admittedly is a little more complicated so we could use something like our drag tracker and have this sort of dragging motion happen around the circle and then map the X&Y position to radius or something and use SVG to draw a circle or something it’s a little more complicated than normal HTML you probably I think you definitely need SVG for this so the underlying JavaScript though we already have right we have tabs we have panels we have a slider might need to tweak some of it a little bit but overall when you come across new fancy UI usually it’s implementing the same underlying behind so this is just kind of helpful tips to not not freak out alright let’s talk about decoupling code so in general these these are guidelines okay there are always rules where you are places where you might need to break these rules but this is how I think of it so hTML is the structure of your app CSS is the style CSS should also be where your animations happen these days animations and transitions are really well supported check your platform for sure but in general I use CSS for all my transitions and animations and then JavaScript is just the behavior and interaction so what this means in practice is that style should only happen in your CSS so what I mean by this is style shouldn’t be happening in your JavaScript so using jQuery CSS method for example if you’re just toggling state doesn’t make a lot of sense keep your keep what your visuals look like in CSS and use add class and remove class and things like that and everything will go much smoother and we’ll do an example in a second to show why in addition animation should only happen in your CSS so there are definitely cases where you have to break this rule but in general putting your CSS or your animations in CSS is much cleaner and again you can you can drive these things by doing add class remove class and you can actually bind to the animation and in transition and events and then lastly JavaScript should care as little as possible about your markup and the structure there always has to be some

link but we’ll get to ways around making that link very tight you want it to be a loose dependency on how much your JavaScript has to know about the structure of your markup so let’s do a quick example sorry too much code let’s go over here so this is just a little to-do list thing I can pump this up real quick really basic we’re all we’re going for in this example is just checking off it to do and then it’s marked as completed and that’s it so let’s just talk real briefly if we wanted to implement that basic behavior how we would decoupled a code so here’s the markup and we’ll walk through this we have the task list we have a task that just consists of a checkbox and then a label for that checkbox so that’s all the mark-up has we switch over to the JavaScript and this is the behavior that we’re looking for right so first thing I do is I grab the checkbox that has to be inside of a task and then on the change event I’m going to check to see if it was actually checked off and if it was I will grab my parent task and I’m gonna add a completed class to it so I just got the checkbox checked and now I’m just gonna mark the task as completed and I’m gonna let CSS decide what that completed state looks like so we can take a look at the CSS it’s pretty basic this is my basic task thing and then here’s the completed state it’s just display:none in this case so the nice thing about this is that any at any point if I need to change the visuals of my application it’s all isolated to my CSS I don’t need to go hunting into JavaScript to find where I called jQuery dot CSS or anything like that so I can change things and I just have to change it in one place so here’s an example of doing an animation and CSS like the example we just saw so instead of displaying done now my completed class has some end properties and then this this keyframe animation fade-out that takes one second so the fade-out animation does fade the opacity for the first part and then shrinks the height for the second it’s all I had to do was update my CSS and the JavaScript doesn’t care because it’s just adding a class it’s just a state marker cool so let’s talk more specifically about the JavaScript I’m kind of what requirements are around writing truly flexible and reusable JavaScript so the two big ones are options and events and what I mean by this is you write a drop a JavaScript component you want to make almost everything possible events have a really robust set of events but also a set of sane defaults you always want some default behavior so the user doesn’t have to know every single possible event that can be overridden and then with the events you want to trigger an external event anytime something significant happens within your component and this leaves the door open for communication between components for anyone who’s interested can listen on to these events and extend the basic behavior so we’ll get to an example in a second so real quick before I show the example I just want to talk about the inheritance we’re gonna go through some code and I want to show you what my base class was and some of the the basic behavior that all these components share so this is my base class so I’m using John Rzeznik simple JavaScript inheritance here s all that means is I’m defining class by using class extend and in it or in it is my constructor so the constructor for my base class takes an element and some options stores the element in a jQuery object and then it takes the options and it overrides any of the defaults and then stores that result in addition ER provides a couple utility methods to do the event emitting and event binding so in this case that’s just using jQuery saying this is a cool hack in jQuery if you guys didn’t know this already you can take a plain JavaScript object wrap it in a jquery call and then you can actually emit events and bind to events on a plain JavaScript object instead of a Dom object so kind of cool so you can pass messages between regular parts of your application or component so let’s take a look at an example so I wanted to come up with something really simple for for the sake of brevity like I don’t want to ton of code on the screen so the basic behavior I came up with for our sample component is just adding and removing a class so we’re gonna Mouse down but like when something Mouse’s down in the element we’re going to add the class and when the mouse goes up we’ll remove the class so mouse down add now step remove so this is what it looks like so I’ve got some animation going on here but all I’m doing is adding in class and removing in class that’s all we’re going for so in this case I’m using it to hide and show something so I call this thing our secret component so this looks like a lot of code to do what we just saw but you’ll see that if you build it out a little more robust you get you get more bang for your buck so let’s let’s walk through what this thing is doing so the first thing our constructor is we call our parents so we get the this dollar element and this dot options set up for us and then we’re doing an event binding so we’re actually notice that the event that I’m binding to is a look up into my options so I said it was Mouse down out of class mouse up removal class but that event name is actually stored in an options object and now I have the ability to tweak that so this is where

the option thing comes in you have this basic behavior this basic idea rather component should act and you can actually leave the door open for someone else to tweak that by just making it an option so up here are my defaults this component the class name that we’re going to be adding and removing is actually an option by default it’s show and then the events in which we add the class and remove the class are also options so default is Mouse down mouse up so again I’m binding to Mouse down and then I’m calling this method apply that’s on the that’s on the component so apply is just doing grabbing the element calling add class and then the class again that it’s adding is a look up in this case it’s show so I just not to mouse down call apply and then I trigger an event to tell anyone that’s interested hey I just applied this class and then I do the same exact thing for remove i bind to this remove event I call remove I trigger an event so that’s the that is the reusable way to write this component that’s the way that I found works and let me show you some examples of what adding a ton of options and a ton of events can do for your application if you want to extend the behavior so here is two of these components that I have on the screen notice that the one on the right behaves the same as I did before and the one on luck does but it’s also driving the one on the right so now I have this master/slave relationship right not the most impressive or useful demo but the whole point is that I took the basic behavior which was add a class remove a class and because I have these events I can actually take advantage of them and have communication between two instances of the components so this is the code that ran that runs what you already have so we have our secret class setup and we just instantiate two of them so one is the one on the left two is the one on the right we bind two secret ones secret apply event so whenever it’s applying it emits this event and then we can rule and then we can reply by saying secret to apply so whenever secret one applies secret two applies same exact thing we’re removed right so now I’ve got this master/slave thing it’s whatever it’s a good example of of how these things can communicate with each other when you leave the door open with these events so next I wanted to show how we can take advantage of some of the options so the options that I had available in this component were the class name and then the events in which we’re adding and removing in class so I kept coming back to using mouse over instead of mouse down and remove a class and then I kept thinking about animation timelines and scrubbing scrubbing an animated gif so what I did is I found an animated gif I broke it up into it’s 91 different frames and I kind of did some HTML and CSS stuff and I just instantiated a bunch of these different components so there’s these little invisible slices and I’ll show them to you in a second overlaid over this image and whenever I’m hovering over one of them it’s actually just adding a class and that toggle is a certain frame of the animation to be shown so this is the result as I hover over I can scrub the animation so the position of my mouse is directly mapped to what frame of the animation is being shown so this is the debug mode again there’s just 91 different slices on top of the image each one of them or only one of them can be active at a time and now I have this a matching image for each one of them it’s a basically a child element and I’m using CSS to say whatever this class is actually applied show the image so that’s all I needed was some HTML and CSS and here is the code that runs that example so I’m just iterating over each slice there happens to be 91 of them so no this is not the most performant most smart way to write an animated gif scrubber but it does work so I ate overall 91 and for each one I instantiate one of these secrets I pass at the element and then I just override those those default option which are mouse down and mouse over or with the defaults our mouse down and mouse up and I do mouse over and mouse out and that’s it so you can add a lot of power to these components if you take the time to buff them out with options and these external events so quick recap blanket statement I should have made a long time ago is this is reflecting us who you know we were rolling our own UI components basically I know that a lot of you guys don’t have the time to do that so if you are out there looking for a good third-party UI component system this is a good rule of thumb of things to look for you want highly configurable and you ideally want your JavaScript to depend very little on what the HTML and CSS are doing and that’s one of the awesome things about this is we can take the same JavaScript and move from project to project and we might different constraints around the markup and the CSS and we can still use the same underlying JavaScript because our JavaScript is all about these patterns and these behaviors so I think that’s it oh sorry one more thing web Pro the framework that I talked about that we use it adobe is not open source but I’ve been kind of kicking the tires with a little open source project so if you

guys want more code samples of some of this stuff you can hit this link it’s also posted on my blog if you just hit ty Ben’s comm and it’s just some more samples of kind of the components that we saw and you can dig into the code and take a look so thank you guys we have