What DOM knowledge should javascript code have?

I am implementing OpenID and OAuth on my site, in C#

and out ASP.NET MVC 3

. I am basing on DotNetOpenAuth for the external and openid-selector for the interface.

I liked the openid-selector , but it doesn't have OAuth support out of the box, so I started adapting it (using StackOverflow 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();
};

      

Both sounds to me like they think too much about the DOM (too many IDs or the current state of the DOM).

Is it good to have javascript tightly coupled to the DOM? What's the best way to avoid code like this and follow a less intrusive approach?

I guess I'm worried about the call:

openid.init('openid_identifier', '', 'http://cdn.sstatic.net/Img/openid/openid-logos.png?v=8', true);

      

When so much is assumed in the script.

+3


source to share


2 answers


I would argue since you suspect this is bad.

There's a huge lack of, well, design patterns in Javascript UI development. I guess a lot of people came straight from html to learn some jQuery in order to write web applications.



A simple system (I find) that does a better job of this is backbone.js. The source code is legible and it separates views quite well from business logic issues.

+1


source


Also, for a more MVVM approach (aka data binding), knockoutjs is an option. They also have a nice interactive tutorial to get you started.



0


source







All Articles