I’m implementing OpenID and OAuth on my site, in C# and ASP.NET MVC 3. I’m basing off of DotNetOpenAuth for the back-end and openid-selector for the front-end.
I liked openid-selector but it doesn’t have OAuth support out of the box so I started adapting it (with help of StackOverflow’s implementation and jsbeautifier).
I found a lot of code that handles the DOM like this:
function highlight(boxId) {
// remove previous highlight.
var highlight = $('#openid_highlight');
if (highlight) {
highlight.replaceWith($('#openid_highlight a')[0]);
}
// add new highlight.
$('.' + boxId).wrap('<div id="openid_highlight"></div>');
};
or
function useInputBox(provider) {
var area = $('#openid_input_area');
var id = 'openid_username';
var html = '';
var value = '';
var style = '';
var label = provider.label;
if (label) {
html = '<p>' + label + '</p>';
}
if (provider.name == 'OpenID') {
id = this.input_id;
value = 'http://';
style = 'background: #FFF url(' + spritePath + ') no-repeat scroll 0 50%; padding-left:18px;';
}
html += '<input id="' + id + '" type="text" style="' + style + '" name="' + id + '" value="' + value + '" />'
+ '<input id="openid_submit" type="submit" value="' + this.signin_text + '"/>';
area.empty();
area.append(html);
$('#' + id).focus();
};
Which both sound to me like they’re assuming too much about the DOM (too many ids, or the current state of the DOM).
Is it ok to have javascript so tightly coupled to the DOM? What’s the best way to avoid code like this and follow a less intrusive approach?
I guess what perplexes me is the call:
openid.init('openid_identifier', '', 'http://cdn.sstatic.net/Img/openid/openid-logos.png?v=8', true);
When there’s so much assuming already in the script file.
I’d argue, as you suspect that this is a bad thing.
There’s a huge lack of, well, design patterns in Javascript UI development. I’m guessing a lot of people came straight from html, to learning some jQuery, to writing web applications.
A simple system (I find) that does handle this better, is backbone.js. The sourcecode is legible, and it separates view-concerns from business logic concerns quite nicely.