Backbone - Router Test

Backbone - Router Test

by Nirvanachain

HTML

<script src="http://underscorejs.org/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<script type="text/template" id="title">
    <h1><%- data[0].name %></h1>
    <a href="#price">Click here to see the price</a>
</script>

<script type="text/template" id="price">
    <p><%- data[0].price %></p>
</script>

<div class="container">

    <div class="row">
        <div class="js-title">
                
        </div>
    </div>

    <div class="row">
        <div class="js-price">

        </div>
    </div>
        
</div>

JavaScript

// Model
var TheModel = Backbone.Model.extend({
	defaults: {
		name: '',
		shortDescription: '',
		price: ''
	}
});

// Collection
var TheCollection = Backbone.Collection.extend({
	model: TheModel
});

// Instantiate a new collection and populate it with some data.
var aCollection = new TheCollection({
	name: 'Mustang',
	shortDescription: 'Pretty nice even if it is overpriced',
	price: '9999'
});

// View for the title
var TitleView = Backbone.View.extend({
	el: '.js-title',

	initialize: function () {
        this.collection = aCollection;
        
		return this;
	},

	render: function () {
		var compiledTemplate = _.template( $('#title').html(), { data: this.collection.toJSON() });
		this.$el.html(compiledTemplate);
			
		return this;
	}
});

// View for the price
var PriceView = Backbone.View.extend({
	el: '.js-price',

	initialize: function () {
		this.collection = aCollection;

		return this;
	},

	render: function () {
		var compiledTemplate = _.template( $('#price').html(), { data: this.collection.toJSON() });
		this.$el.html(compiledTemplate);
			
		return this;
	}
});

// Instantiate a new TitleView
var titleView = new TitleView();
titleView.render();

// Router
var TheRouter = Backbone.Router.extend({
    routes: {
        'price': 'price' // #price
    },

    price: function () {
        new PriceView().render();
    }
});

// Instantiate a new Router
var router = new TheRouter();

// Start browser history
Backbone.history.start();