JSFiddle - React, Tailwind, and code Playground

by Benjamin Lupton

HTML

<script src="http://documentcloud.github.com/underscore/underscore.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone.js"></script>
<script id="form-template" type="text/template">
    <label>
        Please enter someone's name:
        <input class="name-input" />
    </label>
    <span class="actions">
        <input type="submit" class="greet-action" value="Then click me!"/>
        <a class="clear-action">Clear greeting</a>
    </span>
    <div class="greet-message"></div>
</script>

<div id="app"></div>

<p class="footer">Created by <a href="https://github.com/balupton">balupton</a> to showcase an unobtrusive best practice approach to attaching javascript events to buttons/links for <a href="http://stackoverflow.com/questions/134845/href-for-javascript-links-or-javascriptvoid0/9440536#9440536">this stackoverflow answer</a><p>

CSS

a { cursor: pointer; color: blue; }
a:hover, a.hover { text-decoration: underline; }
p,div { margin-bottom: 1em; }
.footer { color: #999; }

JavaScript

(function(window,undefined){

// Define our Form View
var FormView = Backbone.View.extend({
    template: '#form-template',

    initialize: function(){
        // Prepare our template element with underscore,js templates
        this.template = _.template($(this.template).html());
    },

    render: function(){
        // Prepare
        var me = this;
        
        // Render template inside our view's element
        this.$el.html(this.template({}));
        
        // Fetch rendered elements
        var $greetAction = this.$('.greet-action'),
            $clearAction = this.$('.clear-action').hide(),
            $greetMessage = this.$('.greet-message').hide(),
            $nameInput = this.$('.name-input');
        
        // Actions
        $greetAction.click(function(){
            $greetMessage.text('Hello '+$nameInput.val()).show();
            $clearAction.show();
        });
        $clearAction.click(function(){
            $greetMessage.text('').hide();
            $clearAction.hide();
        });

        // Chain
        return this;
    }
});

// jQuery's onDomReady
$(function(){
    // Prepare
    var $app = $('#app');        

    // Render our form view multiple times
    var forms = [];
    forms.push(new FormView().render().$el.appendTo($app));
    forms.push(new FormView().render().$el.appendTo($app));
    forms.push(new FormView().render().$el.appendTo($app));
    
    // Hover shim for IE6 and IE7
    $(document.body).on('hover','a',function(){
        $(this).toggleClass('hover');
    });

});

})(window);