Posts Tagged ‘javascript’

a wishlist for contenteditable

Wednesday, January 5th, 2011

For the past month, off and on, I’ve been working on this text editor. It’s basically functional now, and I stand by my assertion that building bespoke text editors with contenteditable is a worthwhile consideration for sites that need minimal editing options. I even managed to add spell-check. That feature’s only available in IE (I’ll get to why), but that’s fine since built-in spell checking is now the norm and most other browsers include it. However, working this closely with contenteditable has given me a real clear picture of its shortcomings as implemented now, what things I really wish were standard, and what standards I wish browsers were currently equipped to support.

wrap a selection with arbitrary HTML

Initially, formatBlock sounds very promising. Mozilla’s excellent designMode command documentation says developers can use this command to wrap a selection in almost any block-level element. Sadly, those block-level elements, in practice, wrap the entire line that contains the selection instead of separating it out and moving the selection and its parent to a new line. This is in keeping with the behavior of insertUnorderedList, for example, but is annoying because this command doesn’t work any other way. The MDC docs offer em and button as examples of tags you could potentially insert, but in my tests those failed and execCommand returns false. Read a little further in Mozilla’s documentation and you’ll find that IE supports an even smaller subset of HTML tags, which barely even matters because wrapping HTML around a selection is already only useful in such a small number of cases. This pretty much rules out advanced editing or truly being able to use contenteditable to edit a webpage.

wrap a selection with a CSS class

With the exception of IE, browsers carry out commands like bold or italic by wrapping the selection being acted upon in a span with inline CSS specifying the formatting. Wrapping selections in spans (or fonts *cough-IE-cough*) with a class assigned instead of that inline CSS should be pretty easy, but the option just doesn’t seem to be there. I’ve looked. Again, even if you’re of the school that believes contenteditable is just for editing webpages and not for rich text editors or other vulgar uses, this seems like a necessity. It’s not reasonable to expect to offer enough diverse HTML tags that editors will be able to produce whatever functionality and styling they need without having that class for JavaScript and CSS to use as a hook, especially when the tags contenteditable produces differ between browsers.

a designMode command to create a selection

So we don’t beat up on IE too much, I’ll mention right away that IE does have this, and it works pretty well. This, as a matter of fact, is the secondary reason that my text editor ended up only supporting spell check for IE. IE has a command, findText, that takes a string and looks for it in the contenteditable area. This came up prior to the spell check when I was trying to help our automation engineer figure out how to programmatically mimic selecting some text and clicking text editor buttons to format it, so I had to find a solution for Firefox as well. It’s super elegant. You ready? We wrapped the text to be selected in an <i> and used range.selectNode to highlight it. Had this not been automated, that wouldn’t have worked, cause you can’t just type HTML into a contenteditable area, we would’ve had to calculate the offset and length of the selection within it’s containing node or textnode. FYI, once you talk about selections spanning one or more nodes, that ceases to be any fun. It would be great if other browsers would support findText.

my cursor? please?

There’s some strange intialization most browsers seem to require in a contenteditable area. Firefox, for example, will allow you to click into the area and type normally, but you don’t get a cursor until it’s added the <br> that I guess lets it know the area has changes. I’ve been experimenting with various kinds of placeholder text – because putting so much as a space inside the editor allows any browser to click into it normally – but everything I’ve tried is a little screwy. It would be much nicer if offering to let the user create a new text node were a browser’s default behavior in an empty contenteditable area.

for mobile webkit to support it

Or, at least, if mobile webkit is not going to support contenteditable, for it to quit pretending that it does (feature sniffing for execCommand doesn’t work – webkit claims everything is peachy). Clicking into a contenteditable area doesn’t bring up the user’s keyboard. Links within the area continue to function as links, no matter what kind of JavaScript I’ve applied (this may be because I suck). It appears that in mobile webkit all child nodes of the contenteditable area inherit the same bizarre implementation of contenteditable the parent has and become useless buttons. Which is to say, you can attempt to move your cursor into the middle of a text node and instead the text node will be highlighted and you will not get a cursor of any sort. From what I’ve read online, this is a very vexing problem for the developers of these browsers, but I really hope they’re able to figure it out.

for more consistent results

Guess what fontName, fontColor, and fontSize produce in IE? A span with its style attribute filled with font-family:'Comic Sans MS';font-size:70px;font-color:#f0f;? Nope! Give up? It’s font tags! Just like 19-fucking-96. I have not yet installed IE9 because for a long time I didn’t have Windows7, and then I did but I’d stopped caring. Maybe IE9 fixes this. But we all know it’s going to be another decade before IE9’s older siblings go back to the primordial tar pit they crawled out of and until then, using built-in designMode formatting commands means that your user generated content has motherfucking font tags in it. There’s not a lot that can be done about the other browsers and their inline CSS, but my personal wish is that browsers will implement some reserved classes (e.g., .agent-format-italic or something) and attach those instead. Probably best to just be happy that most browsers are using spans, though. But, IE? That font bullshit? Not cool, buddy.



You may feel like this is awfully complainy for someone who started this blog post declaring her modest triumph over this same technology. Like I said, I still think this is loads better than having to download and customize someone else’s editor. But to get my very simple one working, I’ve had to employ some dirty tricks, and that’s the only thing that frustrates me. To wit:

  • Browser-sniffing to get around mobile webkit
  • Wrapping misspelled words in font tags because I can’t use classes or arbitrary HTML
  • That nasty business with selecting text in Firefox I mentioned
  • Having to go through the hidden textarea to strip out HTML comments because either innerHTML or contenteditable won’t admit they’re there
  • Having to insert hrs before and after pasted text so that I can find it and clean up the markup
  • Generally bringing shame upon my family

So I guess let that serve as a warning to you if you decide to go down this path. Although I wish contenteditable were more mature and more standardized, I’ve also had fun working with it. Since we all got JavaScript frameworks and HTML5 and CSS3 support, it’s getting rarer and rarer that it’s necessary to hack something. Dirty and shameful though it’s been, it’s also been interesting.

templates slides, presenting for the first time, and OMG MASSIVE FREAKOUT

Monday, October 18th, 2010

If you’ve been waiting since Refresh for me to post these so you could figure out exactly what I was up there babbling about, they’re now on Slideshare:

And here are the links from the presentation:

Geez. Finally, if you saw the talk, please let me know what you thought on SpeakerRate.

Now I’m gonna talk about my feelings.

There was a break-out session during jqcon hosted by Rebecca Murphey on getting more women speaking at conferences and there were some interesting comments that came out of that on the subject of presenting for the first time. It was interesting to hear what other people who might soon be first-time speakers had to say about why they didn’t jump into it or what confused them. Some of it was the same shit that kept me from jumping into it.

I would never, ever have submitted a talk if Rebecca and Alex Sexton hadn’t been like, “hey, you should try this.” In hindsight, I feel a little ridiculous about that. I’ve been waiting my entire career for someone to say, “you, you’re good enough.” It took hitting my 30s and realizing my options for the future of my career were management or Being More Involved for me to realize that the latter was something I’d really, really wanted for a long time. Modesty is awesome and underrated, especially in developers, but I spent so much fucking time worrying I’d come off like a rockstar developer if I spoke up and claimed to know shit that it kept me from doing what I wanted to do. What I wanted to do was more or less what happened this weekend, minus the freaking out. Wonderful as modesty is, you have to ask whether it’s healthy when it holds you back from an experience like that.

Loving what you do is a qualification. Even if you didn’t work on a site or product everyone has heard of, even if your employer isn’t Twitter or Google, even if you don’t think about code obsessively, you can still be a good developer. I hate seeing articles about what makes a great developer, because they tend to list off totally subjective metrics for gauging your love of this profession. There are only two tests that are worth shit, IMO: whether you write good code and whether it makes you excited. I’ve loved development (mostly) for a long time, but I waited all this time to try and get closer to the source of that excitement, the people and tools that shape this industry. And even when I did, I needed a shove. Kids, don’t be like me.

Speaking at jqcon has made me a better developer. For one thing, the effort I put into making the slides and the demo app that went along with them was possibly the most comprehensive research project I’ve done since college. More tangibly, I finally set up node.js, I posted something on github and made a pull request, and I got real cozy with the template plugin’s source. Additionally, putting your thoughts out there gives people the chance to tell you where you’re wrong. Finding out you’re wrong is awesome, because then you have the opportunity to be right. And just being around the caliber of developer who comes to conferences, who speaks at conferences, is beneficial. Even the conversations I eavesdropped on probably taught me something. You don’t get paid to speak, but you get plenty out of it.

Last night it took me a couple hours to get to sleep cause I was trying to put my finger on what was so terrifying while I was on stage. I finally got it, I think, and this is probably a good thing to note if you’re thinking about speaking at a conference: nobody is looking at you. It’s confusing and unsettling to be standing at the front of a room packed with people who are all staring down at their laptops, notebooks, or telephones. Anything I’ve ever done that’s included being on a stage, I’ve relied on drive-by eye contact with people in the audience to tell me whether or not I’m sucking. I got up there and had a difficult time even spotting anyone looking in my direction (didn’t help that the slides were in the opposite corner of the room), and it was pretty disorienting.

What’s really fucking dumb is that, after my talk, I spent the rest of the conference lost in a myopic haze of shame over the quality of my presentation. It took me pretty much until dinner to distance myself enough to realize that the people who came up and said they were excited about templates weren’t just being nice – that they’d been specific about what they got out of it and had no reason to track me down just to shine me on. All that negativity led to me not being the best ambassador of my topic. My impression of the duty of someone speaking at a conference is that it’s not only preparing the slides and walking everyone through them, but being available throughout the thing to have conversations and further spread your own excitement about whatever subject you spoke on. And I fucking love JS templates, I love talking about using them, I think about front-end development completely differently as a result of having discovered that tool. A part of me wanted to stand in the hallways wide-eyed and eager and tell people personally what I’d said on stage so they’d go back to work and try it out or, whatever, just be amused and maybe have something interesting to think about. I didn’t do that at all, though, and that’s way more shameful than any nervous delivery.

Though I’m mindful of the things I’d need to do differently if I tried this again, I’m done kicking myself. I didn’t do the job I wanted to, but people still learned shit. I missed way more presentations than I wanted to, but I can see them online and I was lucky enough to be in the vicinity of and get to talk to the brilliant folks who put them together. I got to hang out with awesome people I usually only interact with online, met new folks who I’m excited to know, I got pretty good notes from Day 1, and I ate a hell of a lot of seafood. On the whole, the experience was sparkly and wonderful, but I would have gotten a lot more out of it had I not be so self-absorbed about my presentation. (Which is funny cause now I’m writing a whole blog post about it, but I’m reflecting, yo, which is totes important.)

Back to the break-out session.. Whether you’re a woman or not, if you want to speak at a conference, just man or woman up and submit a talk. Don’t be shy about wanting to. If you’re excited about being a developer, you should want to, because you should share the things you know and love so other people can feel the same way. If public speaking actually does terrify you, write a blog, or just post a lot of shit on github. But don’t feel like you can’t participate, cause I did it and I am nobody special. If I can, you can. And if you’re not as good as you’d hoped, it’s ok, then at least you have something to work on. The world isn’t going to end and failure is an excellent teacher.

UPDATE: If you’re considering speaking at a conference for the first time, two really awesome posts you should read:
Rebecca on the Women & Conferences Breakout Session at jqcon, and
Menno van Slooten’s “So you want to speak at a jQuery conference?”

intializing dynamic templates

Saturday, August 28th, 2010

I was noticing the other day that I have some messy fucking templates in code I stepped away from and have recently come back to. This is the result of trying to put all the logic for the HTML produced in the templates, which initially seems like it is a good thing. And it is, for some situations. But consider the case of the element that needs to have an attribute changed depending on the value of some property on the data object, e.g.:

{#if ($T.StupidProperty)}
<input type="checkbox" id="stupidCheckbox" disabled="true"/>
{#else}
<input type="checkbox" id="stupidCheckbox"/>
{#/if}

You can question my syntax, but I feel confident in saying that there are a lot of different ways to write that and they are all, 100%, across the board, ugly. For some things, like elements that should be hidden from users who don’t have administrative rights, or actions that aren’t available after a certain point, this is great and makes sense (but is still ugly). In my application, though, there are a tremendous number of things that get shown and hidden and enabled and disabled dynamically. And there are event handlers in place to manage all that already. After stepping away from this code and then coming back to it, I noticed there was a lot of duplicate logic and a much tidier way to manage it all.

The init function for this application is already a beast and abstracting out the logic in the event handlers and adding calls in the init is most certainly not going to make it any more charming. Worse, it’s going to detract from the self-documenting nature of the templates as they are now. Instead of being able to look at the template and see very clearly how a certain data property may get applied, any future developer will have to track down the form element defining the property and all its listeners. (Thankfully, this will be no big deal if I take the time to deal with documentation in a less half-assed way.)

Those aren’t the reasons I did this in the first place, though. I was thinking about templates in terms of what they’d do if they were server-parsed files rendering only HTML. In this instance I am not running JS on the server, the server doesn’t know these template files from a jpeg of my cat, and that is damned stupid. The templates are Javascript and the event handlers that will eventually turn things on and off dynamically are Javascript. Javascript was put here to serve us. It was not put here to dictate that we keep our templates neatly divorced from our event handlers and that our templates must load the HTML’s correct state in full when we process the template.

I think it’s tricky to say that templates should not be managing state. If you have a situation where the same template might be server-rendered, they most likely should be. Likewise, if all the state changes can be handled with CSS, there’s a better argument for adding the data properties as classes on a container element à la Modernizr. Where those are not the case and some handler will manage the same state once the user begins to interact with the page, however, that logic shouldn’t be in the template.

perfect templates

Wednesday, August 18th, 2010

Last night at Austin JS they tried out a new format where there was only a single talk and then the rest of the time was devoted to an “open forum”. We were handed index cards, and people wrote down questions for the group to discuss. People other than me, at least. I missed that part of the instructions and handed in a card that just said templates!!. It turned out that most of the developers present weren’t using templates, but those who were talked about what they’d worked with and gave some brief opinions. That generated a short but interesting back and forth about whether client-side templates serve any value if you can’t use the same thing on the server-side.

Probably thanks to last night’s discussion, today I was moved to finally finish reading the thread on the jQuery templates proposal, which gets really interesting toward the end. I read the last comment, stared at my screen for a minute or so, and then grabbed my notebook and wrote down what my idea of a perfect client-side templating tool would look like. It looks like this:

<script type="text/html" id="tmplUser">
<h1>${firstName} ${lastName}</h1>
${?premium}
	<img src="premium.gif"/>
${?/}
${#reviewsCount = myNamespace.getReviews(userID).length}
${?reviewsCount > 0}
	${reviewsCount} $ {pluralize("Review",reviewsCount)}
${?/}
${>order=>orders}
	${order.number}
	${order.name}
	${?premium}
		<a href="premiumReturn.html">Return free</a>
	${?}
		<a href="return.html">Return (you pay shipping)</a>
	${?/}
${>/}
${#pluralize=function(word,count) {
	if (count==1)
		return word;
	else {
		var lastChar = word.charAt(word.length-1);
		return (lastChar=='s' || lastChar=='x' ? word + "es" : word + "s");
	}
}}
</script>
...
var data = {
	firstName:"Garann",
	lastName:"Means",
	premium:true,
	userID:9999000,
	orders:{
		[number:321,name:"Mule Variations"],
		[number:543,name:"Library Nation"]
	}
};
someElement.innerHTML = perfectTemplate("templateFile.js",data);

Ok wow, that example looks quite a bit longer typed out than just written on a piece of paper. So I’ll try and keep my explanations of the criteria as pithy as I can.

syntax

I don’t actually have a preference between ${} and any other delimiter. I’ll get to why in a second. But I do like having different delimiters for write: ${}; if: ${?}; nested template: ${>}; and declaration: ${#}. I think an additional one this example neglects is the plain old for loop: ${@}. And I like being able to exit the closest structure by repeating the prefix and just using the slash. Why make the template more complicated by having so many different types of delimiters? Because it allows them to do different things without – for instance – choking on parentheses by giving them explicit direction on what to do with their contents.

external files

In the jQuery templates thread there’s a lot of talk about what the best delimiters are based on what other languages are using. If your template can be loaded from an external file, who the fuck cares what other languages are using? If you’re having ASP.NET parse your Javascript files, you’ve got problems a templating system is not going to fix (hint: try putting your server-rendered constants in their own file and, if you must parse something, parse that). Also, being able to load templates from an external file means you don’t add extra weight to your page for things that may not be used. This would be in addition to, not as a substitute for, loading templates from DOM elements already on the page.

can reference outside objects

I think this is crucial and most templates allow it because they allow Javascript. However, there are some whose syntax seems to imply that they don’t. So, for the record, I’d like to be able to access my own namespaced variables and functions in addition to frequently referenced things like length.

declarations (?)

Honestly I am not completely sold on this either. Just declaring variables and not functions or objects might be a middle ground worth considering, though.

Why it seems like a good idea:
1) It keeps you from having to repeat the same chain of objects or functions to get a property that’s used repeatedly.
2) It would be nice to declare functions specific to your template that manipulate pure data for presentation.

Why it seems like a bad idea: at that point you almost might as well just write a big string concatenation function and give up on templates. That is, there’s no limit to the amount of programmatic logic embedded in the template, which is probably not desirable.

nested templates

jTemplates uses named templates that aren’t nested, and I found that pretty useful in terms of being able to separate different structures for readability. However, there was one caveat that really pissed me off, which was that I couldn’t easily refer to an object’s parent from within a template called on a property of that parent. I think it’s less readable but more useful for sub-templates to remain nested within their context, and thus remain aware of their parent. You could still do this with named templates, but I think that would be really confusing.

This point is as much about this as it is about nesting. jTemplates didn’t work for me because it changed the definition of this in each template. I would prefer to see this always be the object passed in to the template when called, and e.g. an element in an array to be given its own named variable for easy reference while in the context of a child template.

easy use

For flexibility, I think a template should take the template and a data object and spit out a string. The developer should have full control over how and where that string gets added to the DOM.

no viewmodel

My personal, possibly crazy, opinion is that viewmodels are worthless. Creating a specific object for every scenario where you need to apply data to your View means you get a lot of repeated data spread across many many different viewmodels. You could argue that getting raw data and running the same property through a global function for each is no better, but I see one big difference. I’ve never worked with a viewmodel where I didn’t have to apply some transformation for the sake of the View to some property. You can fucking quote me. Experience has taught me to assume there will always be something and that committing yourself to adding a property to the viewmodel every time Something comes up is a Sisyphean task. Therefore I believe strongly in getting the username from the same function each time it’s used. If you use it more than once in the same context then, yeah, put it in a variable, but a variable local to that context, not one that’s forever stuck to the viewmodel. Data should be pure and flexible.

programmatic logic in the template

Look, there are some very pretty templating syntaxes out there, but the prettiest seem to offer the least control over how the data gets applied. As far as I’m concerned, a template is just string concatenation in context, and that’s what it should be – it needn’t try to approximate markup. It’s a helper that allows you to keep your objects cleaner and to reuse code more easily. Insisting that it should be readable is silly. If you want readable, make it a server-side include and hydrate it property by property. A template allows you to abstract out logic that is specific to the display of the markup that template produces, and therefore should be as logically complex as it needs to be to accomplish its task.

part two?

The point of this very lengthy exercise? Defining exactly what I should be looking for. Hopefully, having done that, I can now start exploring the templating systems I don’t currently have any exposure to and evaluating them for my own use. The plan is that this will be continued and I’ll run down the options that exist and – with luck – discover one that’s a perfect fit. But if you know the answer and want to save me the research, please, have at it:

parentheses in jquery-tmpl

Wednesday, August 11th, 2010

Apparently jquery-tmpl doesn’t like parentheses in IE.

Damn near went back to jTemplates for my work project yesterday, because jquery-tmpl was shitting the bed in IE and no one could figure out specifically why. We were going to write it off as not done enough to use, but after looking at the code I’d have to change because jTemplates requires a container to load into where jquery-tmpl can use appendTo(), I decided it was worth doing some process of elimination first. The issue turned out to be parentheses I was using in conditionals, i.e.:

{{if (user == loggedInUser)}}

Removing the parentheses allowed the scripts to run normally in IE and didn’t cause any other problems. However, I worry what could happen if the parentheses weren’t just a syntactic preference, but were actually necessary. What if I were, like, doing math?

I didn’t find anything when I googled the issue, so I thought I’d note this caveat here. I’m sure it’s temporary, but if you’re also using those templates.. now you know!

model-view-controller and roomy clothes

Monday, August 9th, 2010

It finally happened. .NET MVC and I came to blows, and are no longer speaking. This is super awkward, as we still have to work together. And, you know, part of me thinks it’s possible that I’m not being entirely fair, that I’m judging .NET MVC solely on the way it’s behaving right now and it actually has more to offer and we might even be able to get along, were circumstances different. Another part of me thinks that they’re not different and I am tired of .NET MVC’s bullshit, situational or otherwise.

The further I move away from backend development, the more I find myself wanting to use Javascript on the serverside. In this specific case, my reasons are simple and selfish: I want dynamically typed objects. Whether it’s an innate property of the framework or not I don’t know, but .NET MVC seems to be built around the idea of a one-to-one relationship between data objects and the pages that display them. As I’m seeing it used right now, it would be very good for some WinForms desktop app where every new screen represents a single table in the database, but it is just shit for webpages that pull little bits of various models in from all over the place and try to offer functionality spread across different controllers. My thinking is that if a View can truly be said to need to know nothing about the Model that hydrates it, the developer working on the View should not have to be intimately familiar with the Model to do her job. Nor should she have to wait for a backend guy to free up in order to get some data added to the object used by the page she’s working on. Data should be provided by the Controller and the View should be able to grab what it needs without an act of god.

Yeah, I know, the View should be dumb. Eff that. This is 2010, this is the web, and the View is pretty much the application. To say one page must commit itself to one server-defined type of data and cannot go out and forage through the controller for other information it needs is just.. nuts. I don’t see how Model-View-Controller can work on complex, interaction-heavy websites without a little more flexibility in its definition.

The utility I see in the MVC pattern is in separating frontend logic from backend logic, in enforcing loose coupling. The View and Model should both interact with the Controller, totally agree with that. I think pretty much everybody does. Where opinions and definitions begin to diverge, I think, is in how much control the View and Model themselves have over their own domains. As far as I’m concerned, it should be limitless. The Controller’s job on the GET is to package the data, to expose useful helper methods that do things like loop through the customer’s history to find out which songs she’s already favorited or which books she’s purchased. On the POST, its job is to double-check the View’s validation and return an error if the customer tried to order a band saw that just sold out.

The biggest issue I have with .NET MVC as I’m seeing it used is that the controllers do not write helper methods. Their methods either provide or receive entire pages, and I don’t see the value in a one-to-one relationship between methods and pages. There are some “HtmlHelpers”, but these provide actual markup and I don’t think that’s any of the backend’s goddamned business. The issue I have with MVC as I’ve seen it applied to a variety of languages is the notion that a Controller should be in charge of serving pages. Horseshit. The View should be in charge of serving pages. It knows more about them and more about the client consuming them.

I don’t know if this makes me a lunatic or what. I do know that prior to .NET MVC, me and a woman I worked with wrote our own MVC in .NET using this basic philosophy and it seemed to work fine. It was well organized, loosely coupled, and flexible enough that I didn’t spend entire workdays wanting to throw things.

..Which kind of leads into a related topic: something very interesting Rebecca Murphey posted today on jQuery in large applications. It got me thinking, because I both agree and disagree. I think it’s important that people’s skills progress beyond simple DOM manipulation, but I find the idea of an all-in-one solution for large applications difficult to swallow, perhaps because of the experiences I’ve had with those sorts of setups in backend languages. Yes, they promote better coding practices and provide structure and predictability. But my personal experience has been that there’s a trade-off in terms of flexibility.

I worked with YUI for a while and it left me with a preference for jQuery. Not for very complex reasons – I just felt that the things I wanted to use most, functions for building objects and wiring up events, were exactly as difficult to get to as the things I never used, the wide variety of widgets YUI contains. Additionally, I had problems with many of the widgets. They were all very nice and pretty reliable, but when I tried to push them beyond the examples given in the documentation, I was getting about a 50% success rate (again, I was using very few of the widgets, so grain of salt, please). This is why I ended up rewriting the last application I worked on in jQuery, doing exactly the thing described in the post: piecing together a custom cocktail of templates and patterns to suit my own needs. At the risk of disagreeing with very smart people, I thought this was awesome. I had what I needed, nothing I didn’t, and the setup lent itself very well to roll-your-own solutions.

It may seem I’m intentionally missing the point, but I do understand the problem with roll-your-own solutions. I do agree that it benefits everyone to be working in the same setup and making use of tools that have been vetted by geniuses whose entire job is to create such things. But I’m dubious about any approach which comes too close to promising one size fits all. If you’ve ever sewn a dress, you understand that one size fits all is technically possible, but some people are going be left with a lot of excess while others will scarcely be able to breathe.

Frequently when we talk about architectures, we talk about the ability to scale, and we mean scale larger. I don’t think enough thought goes into scaling smaller. If I could have stripped down YUI on my old project, made the nuts and bolts more accessible while getting rid of the tile saws and routers, I would have done that. But it took less time to just rewrite the damned thing in jQuery, and left a more maintainable product. I’m not sure it’s possible to scale smaller. With that in mind, I think it’s best to start with the most nimble tool that can do the job.

I guess this is still more about .NET than it is about Javascript, though it’s the reason some of what Ms. Murphey is advocating makes me nervous. If we’d done what we’re doing at work right now with ugly, messy, oldschool code-behind pages I think we’d have a better codebase. I think we could have gotten all the benefits of MVC without the branding, I think the frontend people would be less reliant on the backend people, I think we’d be able to make changes more quickly, and I think we’d be a hell of a lot better off. In every language there are patterns and frameworks that promise a better, cleaner, more comprehensive way of doing things, and that no doubt will deliver, assuming what you want to produce is what they’re meant for. But if you try to get them to produce something different, all they deliver is a bigger mess.

In conclusion, consider the bespoke suit. The quality is less reliable than something made in a factory by perfectly calibrated machines. No groups of fashion experts have gone over its every detail to make sure each is the best it can be. You cannot get a new one exactly like it, only in navy. If your tailor retires, anyone else you let touch it is probably going to ruin it. But you know what? The motherfucker fits.

delegate and actually thinking

Friday, August 6th, 2010

It’s been kind of a rough month. Inspiration has been hard to come by, which is why this blog has been a little quiet. The project I’m on at work is chaos and most of the time I feel like a code monkey. No new technologies, no interesting experiments, nothing fun to think about. But there’s been a high point.

jQuery’s delegate has been my personal plate of shrimp lately. Another developer I know in town mentioned she was having some problems with it – prior to that I’d never even heard of it and had been quite content to go along using live for everything. As a result I started talking about it with my neighbor at work, and then he linked me to some blog posts comparing it to live. Then it came up in a few other places. Now it’s all over our Javascript at work. Crazy!

During this period, there has been a lot of figuring things out and I have come to like delegate quite a bit. I like it because – unlike many things in jQuery – it’s not all super-accepting and magical. You actually have to think about how you’re using it. And thinking about it is not some ascetic endeavor, like coding in Perl or something. There’s a real benefit to thinking it through and using delegate instead of live or bind. Sometimes using a library like jQuery makes me feel I’m not really in control of my code and I miss the old days when we did it all by hand. Using delegate, by comparison, actually feels like the tools are helping me improve the quality of my code without sacrificing my ability to make choices about how it does things.

Sometimes really trivial stuff makes me enormously happy. I’m a dork.

One of the coolest things is that I’ve gained is an understanding of live, which I’ve relied on heavily but had never given much thought to. Now that I know how it and delegate work, both seem at once brilliant and obvious. Why listen to a gazillion little anchor tags when you can listen to their container and wait for them to bubble up? I wish I’d heard about this method ten years ago. I don’t know, maybe events didn’t bubble the same way then. It’s been educational also in terms of learning which events do and do not bubble. There are a lot of things I’d like to go back and refactor, armed with this knowledge.

I’ve “flipped through” jQuery Fundamentals, but this has left me feeling I should devote a weekend to reading the whole thing. There’s so much I miss just looking at API documentation for things I’m already using. It’s really nice to discover something rad I’d overlooked, and to actually have to think about it.

jQuery templates (plus a pony)

Wednesday, July 21st, 2010

The jQuery templates proposal makes me really excited. I love jTemplates and all, but support seems sparse. And I know other cool alternatives – for jQuery and for other libraries, as well as homegrown solutions – exist. But jQuery is what I use at work and so I’m happy templates are being considered for addition. I’m hopeful that this will result in a rock solid implementation and some really cool extensions.

I already switched the jTemplates stuff in my work project over to the latest branch of jquery-tmpl, and thought I’d add it to the front page of this site, too. It’s sort of a weird application, because the front page data is static and doesn’t really need templates. As a matter of fact, the one thing it did need, jquery-tmpl (someone please correct me if I’m calling it the wrong thing) doesn’t include. However, with a minor modification, I was able to get it to do what I needed, and have the currently static markup already parsed as a template so that in the future I can easily make it more dynamic.

The changes I wanted to make involved loading each frame of the animation/paper doll thing on the front page on demand, instead of having them all there in the page when it loads. This is part one in a two-part attempt to make it not run like total shit on mobile. I moved all the extra frames off into their own pages, and could easily at that point have just gotten them one by one with $.get(). But, as mentioned, I wanted to load them as templates for flexibility down the line (ex: translations, because many people in many nations are interested in my hobbies and my dog and cat). So I did this:


$.extend({
tmplFromUrl: function( url, data, callback, options, parentItem ) {
$.get(url,function(response) {
var tmpl = $.tmpl(response, data, options, parentItem);
callback(tmpl);
});
}
});

Called like this:

$.tmplFromUrl(url, null, function(tmpl) {
nextPage = tmpl.appendTo(container);
garanndotcom.flipPages(currentPage,nextPage);
});

Even though that’s totally boneheaded for this particular application, the ability to load data from an external file is something I’m really hoping they add. I never used it in my big jTemplates application (cause every page was one big template), but it was something I was hoping to use on my current work project. I don’t mind using my own goofy plugins to get the same effect, but I doubt I’ll be the only person to ever want this and it seems silly to have a bunch of different people writing a bunch of different code that’s probably going to amount to less than ten lines apiece. Maybe there’s a good reason they don’t want to add it (security seems like it might be one) – I haven’t made it to the bottom of the discussion thread about templates yet. Personally, I’m hopeful that they just haven’t gotten around to it yet.

tracking focus on multiple objects

Friday, July 9th, 2010

You remember that time period when website navigations of all types had to be in drop-downs? Remember when they’d be like two, three levels deep, pretty much your whole damned site map stretched out across the top or down the left of your page? I remember that. And during that time, I remember running into a problem that plagues me to this day. I was using Dead Edwards’ IE7 to get :hover to work, I think, and still running into problems because IE was interpreting my mousing over a child element as equivalent to mousing out of its parent. I find it annoying that this is still an issue.

I was trying to implement an autocomplete jQuery plugin at work today and was dismayed that I had apparently broken it by putting overflow:auto and a height on the faux dropdown of results. Clicking on the scrollbar (thus out of the input field) hid the results div. I was able to fix it using the code below, but then the damned thing would hide itself if I scrolled and then tried to click one of the results to select it:

$input
.focus(function(){
// track whether the field has focus, we shouldn't process any results if the field no longer has focus
hasFocus = true;
})
.blur(function() {
// track whether the field has focus
hasFocus = false;
if (!resultsHasFocus) {
hideResults();
}
});
$results
.mouseover(function(e) {
resultsHasFocus = true;
})
.mouseout(function(e) {
resultsHasFocus = false;
if (!hasFocus) {
hideResults();
}
});

Fortunately, my neighbor in the cube village at work is Mr. Cravey, and I was able to turn to him and ask him if he knew how to get IE to stop misinterpreting my mouse movements (he did – substitute mouseenter and mouseleave for mouseover and mouseout, something I cannot believe I lived this many years without knowing). Strangely enough, he had the code right in front of him because he was working on a very similar problem.

And so we had an interesting discussion about how you track explicit and implicit focus (i.e., clicking and hovering) across multiple different objects in order to determine when to toggle state. I kept the approach above, setting flags, because the elements I needed to track focus in didn’t share a container. His did, and required only explicit focus, so I believe he ended up using focusin and focusout. We sort of agreed that, once this problem gets sufficiently complex, there’s no solution for it that isn’t kind of dirty. Setting flags seems like it shouldn’t be necessary, but it’s a very obvious way for separate elements to inform each other of their state so that one doesn’t go toggling something the other isn’t ready to have toggled yet. I was thinking about custom events, but honestly that feels like a more palatable version of the same concept, like the old cat food commercial where the cat food has been mashed up and adorned with a sprig of parsley.

Kind of dancing around the real issue here, which is not actually the focusing, but the blurring. Assuming what you want to toggle is show and hide, you put a little close button on that shit and none of this is an issue anymore. The real problem is that any member of the set of tracked elements can opt in on behalf of all of them, but they all need to explicitly opt out.

I know what seems like the most comprehensive solution to me, but it’s not very elegant.. It would be thorough, though, to put your series of objects in an array and attach handlers for both implicit and explicit focus and blur to the array itself. I could see that taking a long time, though, since you’d have to check whether anything in the array had focus every time something within the array lost or received it. Practically, the best thing to do is probably to use Cravey’s method even in cases where it means adding an extra wrapper element. One extra tag is really not so bad when compared to any alternative I can think of.

the jTemplates experiment

Wednesday, June 9th, 2010

So it took a heck of a long time between the first proofs of concept and actually going live, but I rewrote a pretty complex client-based web application to use jTemplates. It started out with 12k+ lines of code (the numbers in that previous post don’t reflect various utility files, just the two main ones) and when I totaled it up on Monday, the new count is 3834. I’d been estimating it at about 5k. Less than 4k is better than I’d hoped. Even more impressive is that the previous figure did not include all the HTML templates that provided the pages their basic structure – the 3834 includes the jTemplates (since they’re all Javascript), meaning that’s it.

Summary: I am now a fanatical jTemplates convert.

However, I had a conversation over the weekend that’s got me questioning whether I’m sacrificing too much performance for maintainability. I won’t pretend the new application runs a lot faster than the old one. Its issues are different – this takes a long time to load, whereas the old one leaked memory over time – but it’s not blazing fast by any means. Part of the problem is the immense data object that the jTemplates process. All the information about a specific object is passed down at once when the page first loads, and then has to be pulled down again whenever the user switches between the four tabs in the application because of some irritating issues with the web services (the only thing they return is error messages, so if a new element is added, for example, it takes an additional XHR to find its ID) and data getting stale. I’m wondering, if I’m pulling down all this data anyway, if there’s an argument for putting jTemplates on the server and just getting the markup pre-loaded with the data points.

Of course, this is a .NET environment where I have pretty much no control over the backend, so it’s not likely I’ll get to try jTemplates on the server. I can’t find evidence that anyone’s ever tried that, so who knows, maybe it’s impossible.. Instead I’m going through all my notes from txjs and applying every performance enhancement I can find to any code I’ve touched over the past couple days. It’s not giving me an improvement so far, and I’m beginning to feel this is a design problem. If there were a way to split up the data being pulled down and lazy load interface elements, I think things would speed up a lot. Sadly, there’s (currently) not.

I’m left with 4k lines of Javascript I’m very pleased with having shrunk and no clear path forward, which fucking sucks. But the application is clearer and more well organized. I guess the experiment continues..