Search code examples
javascriptjsonbackbone.jsunderscore.js

how to populate backbone collection from json using button


I have large collection of json objects which I retrieve through a search function, though depends on the search string, the output can go up to more than thousand of arrays which I populate into a list. Within mobile environment this become a hassle and memory consuming once I add touchmove, touchstart and touchend to each object. I found solution to this that there's a minimal way of showing object using backbone.js and with trigger such as button this could become robust. though I don't know how to go foward with it. This is working example without the button. And how I shoud do this?

<script>
    //model - define value objects.
    var Client = Backbone.Model.extend({
        defaults: {
            name: 'cole',
            age: '12'
        }
    });
    //collection - load json
    var ClientCollection = Backbone.Collection.extend({
        defaults: {
            model: Client
        },
        model: Client,
        url: './json/test.json',
    //override parse due to json format. point to "items"
        parse: function (response, xhr) {
            return response.items;
        }
    });
    //view. init collection. listen for data to be loaded. render.
    var ClientView = Backbone.View.extend({
        initialize: function () {
            this.collection = new ClientCollection();
            this.collection.bind("reset", this.render, this);
            this.collection.fetch();
        },
        render: function () {
            //append to html here ...
            //alert(this.collection.at(0).get("name"));
            //alert(this.collection.length)
            for (var i = 0; i < this.collection.length; i++) {
                $('#append-el').append('<li>' + this.collection.at([i]).get("name") + '; ' + this.collection.at([i]).get("age") + '</li>')
            }

        }
    });
    var clientView = new ClientView();

</script>

<div id = "append-el"></div>

Solution

  • Add an event listener to your view pointing to your button with the events hash, something like this

    ,events {
       "click #buttonID" : "fillCollection"// <- this is a method name
    }
    

    and then create this method and trigger a collection.fetch, like this

    ,fillCollection: function(){
        this.collection.fetch();
    }