Backbone - Collection fetch call incrementing

Backbone - Collection fetch call incrementing

by Nirvanachain

HTML

<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<div>
    <ul class="nav">
        <li>
            <a href="#pageone">Page One</a>
        </li>
        <li>
            <a href="#pagetwo">Page Two</a>
        </li>
    </ul>
</div>

<div class="js-container">
</div>

<script type="text/template" id="One">
    Color = <%- collection.models[0].attributes.color %>
</script>
    
<script type="text/template" id="Two">
    Click the link "Page One" and check the console to see the fetch call for the collection incrementing.
</script>

CSS

.nav { 
    text-align: center;
}
.nav > li {
    display: inline-block;
}

.nav > li > a {
    text-decoration: none;
}

.nav > li > a:hover {
    text-decoration: underline;
}

JavaScript

var MyModel = Backbone.Model.extend({
    defaults: {
        'id': 'null',
        'color': '',
        'date': '',
        'name': ''
    }
});

var MyCollection = Backbone.Collection.extend({
    model: MyModel,
    
    url: 'https://api.mongolab.com/api/1/databases/testdatabase/collections/Content?apiKey=qcVNgNb-s1X4WJkLeRDfykxqtMG-ezkC'
});

var aCollection = new MyCollection();

var MyViewOne = Backbone.View.extend({
    el: '.js-container',
    
    initialize: function () {
        
        this.collection = aCollection;
        
        this.listenTo(this.collection, 'sync', this.render);

        this.collection.fetch();
    },
    
    template: _.template( $('#One').html() ),
    
    render: function () {
        console.log('render One');
        console.log(this.collection);
        
        this.$el.html( this.template({collection: this.collection}) );
        
        return this;
    }
});

var MyViewTwo = Backbone.View.extend({
    el: '.js-container',
    
    template: _.template( $('#Two').html() ),
    
    render: function () {
        console.log('render Two');
        
        this.$el.html( this.template() );
        
        return this;
    }
});

var MyRouter = Backbone.Router.extend({
    routes: {
        '': 'pageOne',
        'pageone': 'pageOne',
        'pagetwo': 'pageTwo'
    },
    
    pageOne: function () {
        var myViewOne = new MyViewOne(); 
    },
    
    pageTwo: function () {
        var myViewTwo = new MyViewTwo();
        myViewTwo.render();
    }
});

var myRouter = new MyRouter();
Backbone.history.start();