Backbone.js Introduction to Views

by ifandelse

HTML

<script src="http://documentcloud.github.com/underscore/underscore.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone.js"></script>
<script id="view1Template" type="text/html">
    <div>
        <h2>Introducing Backbone View #1</h2>
        <em>This view is targeting an existing DOM element</em>
    </div>
</script>

<div id="view1"></div>

CSS

.blue-stuff {
    background-color: lightsteelblue;
    color: midnightblue;
    font-family: Arial, sans-serif;
    font-size: 10pt;
}
div {
    margin-bottom: 20px;
    padding: 5px;        
}

JavaScript

var BaseView = Backbone.View.extend({
    selectors: {},

    locate: function(selector) {
        if (this.selectors.hasOwnProperty(selector)) {
            return this.$(this.selectors[selector]);
        }
    }
}),
    View1 = BaseView.extend({
    el: "#view1",

    selectors: {
        headers: "h2",
        emphasis: "em"
    },

    initialize: function() {
        // using the initialize to grab the template
        // text and cache it on the view object
        this.template = $("#view1Template").text();
    },

    render: function() {
        // this.$el provides jQuery object for the view's element
        this.$el.html(this.template);
        // this.$ provides jQuery selector function scoped to the view
        this.locate("emphasis").css({
            "font-family": "Verdana",
            "font-size": "48pt"
        });
    }
});

view1 = new View1();
view1.render();