Backbone Live Collection End Point Fetch - add overwrite

by Alee

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.1/backbone-min.js"></script>
<script type="text/template" id="search_template">
  <label>Search</label>
  <input type="text" id="search_input" />
  <input type="button" id="search_button" value="Search" />
</script>
<script type="text/template" id="result_template">
  <b><%= name %></b> 
</script>

<div id="search_container"></div>
<div id="result_container"></div>

<div id="example_content"></div>

JavaScript

// A container for a repo object.
var Repo = Backbone.Model.extend({});

// A basic view rendering a single repo
var RepoView = Backbone.View.extend({
    tagName: "li",
    className: "repo",
    render: function() {
        /*$(this.el).html(
            '<b>' + this.model.get("name") + "</b> - " +    
            this.model.get("description")
          );*/
        var tpl = _.template( $("#result_template").html() );
        this.$el.html( tpl(this.model.toJSON()) );
        
        return this;
    }
});


// A collection holding many repo objects.
// also responsible for performing the
// search that fetches them.
var Repos = Backbone.Collection.extend({
    model: Repo,
    initialize: function(models, options) {
        this.language = options.language;
    },
    url: function() {
        return "https://api.github.com/search/repositories?q=language:" + 
               this.language + "&sort=stars&order=desc";
    },
    parse: function(data) {

        // note that the original result contains repos inside of an items array, not at 
        // the root of the response.
        return data.items;
    },
    add: function(models, options) {
        var newModels = [];
        _.each(models, function(model) {
            if (typeof this.get(model.id) === "undefined") {
                newModels.push(model);
            }
        }, this);
        return Backbone.Collection.prototype.add.call(this, newModels, options);
    }
});

// A rendering of a collection of tweets.
var ReposView = Backbone.View.extend({
    tagName: "ul",
    className: "repos",
    initialize: function(options) {
    		this.listenTo(this.collection,'request', this.ajaxStart);
        this.listenTo(this.collection,'sync', this.ajaxComplete);
        this.collection.bind("add", function(model) {
            var repoView = new RepoView({
                model: model
            });
            $(this.el).prepend(repoView.render().el);
        }, this);
    },
    render: function() {
 ...