Question

Quick summary of my problem: first rendering of the view contains the elements in the collection, and the second rendering doesn't. Read on for details...

Also of note: I do realize that the following code represents the happy path and that there is a lot of potential error handling code missing, etc, etc...that is intentional for the purpose of brevity.

I'm pretty new with backbone.js and am having some trouble figuring out the right way to implement a solution for the following scenario:

I have a page shelled out with two main regions to contain/display rendered content that will be the main layout for the application. In general, it looks something like this:

-------------------------------------------
|                          |              |
|                          |              |
|         Content          |   Actions    |
|          Panel           |    Panel     |
|                          |              |
|                          |              |
|                          |              |
|                          |              |
|                          |              |
|                          |              |
-------------------------------------------

I have an HTTP API that I'm getting data from, that actually provides the resource information for various modules in the form of JSON results from an OPTIONS call to the base URL for each module. For example, an OPTIONS request to http://my/api/donor-corps returns:

[
    {
        "Id":0,
        "Name":"GetDonorCorps",
        "Label":"Get Donor Corps",
        "HelpText":"Returns a list of Donor Corps",
        "HttpMethod":"GET",
        "Url":"https://my/api/donor-corps",
        "MimeType":"application/json",
        "Resources":null
    }
]

The application has a backbone collection that I'm calling DonorCorpsCollection that will be a read-only collection of DonorCorpModel objects that could potentially be rendered by multiple different backbone views and displayed in different ways on different pages of the application (eventually...later...that is not the case at the moment). The url property of the DonorCorpsCollection will need to be the Url property of the object with the "GetDonorCorps" Name property of the results of the initial OPTIONS call to get the API module resources (shown above).

The application has a menubar across the top that has links which, when clicked, will render the various pages of the app. For now, there are only two pages in the app, the "Home" page, and the "Pre-sort" page. In the "Home" view, both panels just have placeholder information in them, indicating that the user should click on a link on the menu bar to choose an action to take. When the user clicks on the "Pre-sort" page link, I just want to display a backbone view that renders the DonorCorpsCollection as an unordered list in the Actions Panel.

I'm currently using the JavaScript module pattern for organizing and encapsulating my application code, and my module currently looks something like this:

var myModule = (function () {

// Models
    var DonorCorpModel = Backbone.Model.extend({ });

// Collections
    var DonorCorpsCollection = Backbone.Collection.extend({ model : DonorCorpModel });

// Views
    var DonorCorpsListView = Backbone.View.extend({
        initialize : function () {
            _.bindAll(this, 'render');
            this.template = _.template($('#pre-sort-actions-template').html());
            this.collection.bind('reset', this.render); // the collection is read-only and should never change, is this even necessary??
        },

        render : function () {
            $(this.el).html(this.template({})); // not even exactly sure why, but this doesn't feel quite right

            this.collection.each(function (donorCorp) {
                var donorCorpBinView = new DonorCorpBinView({
                    model : donorCorp,
                    list : this.collection
                });

                this.$('.donor-corp-bins').append(donorCorpBinView.render().el);
            });

            return this;            
        }
    });

    var DonorCorpListItemView = Backbone.View.extend({
        tagName : 'li',
        className : 'donor-corp-bin',

        initialize : function () {
            _.bindAll(this, 'render');
            this.template = _.template($('#pre-sort-actions-donor-corp-bin-view-template').html());
            this.collection.bind('reset', this.render);
        },

        render : function () {
            var content = this.template(this.model.toJSON());
            $(this.el).html(content);
            return this;
        }
    });

// Routing
    var App = Backbone.Router.extend({
        routes : {
            '' : 'home',
            'pre-sort', 'preSort'
        },

        initialize : function () { },

        home : function () {
            // ...
        },

        preSort : function () {
            // what should this look like??
            // I currently have something like...

            if (donorCorps.length < 1) {
                donorCorps.url = _.find(donorCorpResources, function (dc) { return dc.Name === "GetDonorCorps"; }).Url;
                donorCorps.fetch();
            }

            $('#action-panel').empty().append(donorCorpsList.render().el);
        }
    })

// Private members
    var donorCorpResources;
    var donorCorps = new DonorCorpsCollection();
    var donorCorpsList = new DonorCorpsListView({ collection : donorCorps });

// Public operations
    return {
        Init: function () { return init(); }
    };

// Private operations
    function init () {
        getAppResources();
    }

    function getAppResources () {
        $.ajax({
            url: apiUrl + '/donor-corps',
            type: 'OPTIONS',
            contentType: 'application/json; charset=utf-8',
            success: function (results) {
                donorCorpResources = results;
            }
        });
    }

}(myModule || {}));

Aaannnd finally, this is all using the following HTML:

...
<div class="row-fluid">
    <div id="viewer" class="span8">
    </div>
    <div id="action-panel" class="span4">
    </div>
</div>
...
<script id="pre-sort-actions-template" type="text/template">
    <h2>Donor Corps</h2>
    <ul class="donor-corp-bins"></ul>
</script>

<script id="pre-sort-actions-donor-corp-bin-view-template" type="text/template">
    <div class="name"><%= Name %></div>
</script>

<script>
    $(function () {
        myModule.Init();
    });
</script>
...

So far, I've been able to get this to work the first time I click on the "Pre-sort" menu link. When I click it, it renders the list of Donor Corps as expected. But, if I then click on the "Home" link, and then on the "Pre-sort" link again, this time I see the header, but the <ul class="donor-corp-bins"></ul> is empty with no list items in it. ... and I have no idea why or what I need to be doing differently. I feel like I understand backbone.js Views and Routers in general, but in practice, I'm apparently missing something.

In general, this seems like a fairly straight-forward scenario, and I don't feel like I'm trying to do anything exceptional here, but I can't get it working correctly, and can't seem to figure out why. An assist, or at least a nudge in the right direction, would be hugely appreciated.

Was it helpful?

Solution

So, I've figured out a solution here. Not sure if its the best or the right solution, but its one that works at least for now.

There seems to have been a couple of issues. Based on Rob Conery's feedback, I started looking at different options for rendering the collection with my view template, and this is what I came up with:

As I mentioned in the comment, we're using Handlebars for view templating, so this code uses that.

I ended up changing my view template to look like this:

<script id="pre-sort-actions-template" type="text/x-handlebars-template">
    <h2>Donor Corps</h2>
    <ul class="donor-corp-bins">
    {{#each list-items}}
        <li class="donor-corp-bin">{{this.Name}}</li>
    {{/each}}
    </ul>
</script>

Then, I removed DonorCorpListItemView altogether, and changed DonorCorpsListView to now look like this:

var DonorCorpsListView = Backbone.View.extend({
    initialize : function () {
        _.bindAll(this, 'render');
        this.collection.bind('reset', this.render);
    },
    render : function () {
        var data = { 'list-items' : this.collection.toJSON() };
        var template = Handlebars.compile($('#pre-sort-actions-template').html());
        var content = template(data);
        $(this.el).html(content);

        return this;
    }
});

So, that seems to be working and doing what I need it to do now.

I clearly still have a lot to learn about how JS and Backbone.js work though, because the following DOES NOT WORK (throws an error)...and I have no idea why:

var DonorCorpsListView = Backbone.View.extend({
    initialize : function () {
        _.bindAll(this, 'render');
        this.template = Handlebars.compile($('#pre-sort-actions-template').html());
        this.collection.bind('reset', this.render);
    },
    render : function () {
        var data = { 'list-items' : this.collection.toJSON() };
        var content = this.template(data);
        $(this.el).html(content);

        return this;
    }
});

Hopefully this will be helpful to someone.

OTHER TIPS

Your rendering code looks odd to me for the DonorCorpListView - it looks like you're templating before you have any data. You need to compile that template with the data to get the HTML output.

So, the rendering logic should be somthing like:

var template = $([get the template).html();
template.compile(this.collection.toJSON());
this.el.append(template.render());

I used some pseudo code here as I'm not sure what your templating mechanism is (I like Handlebars myself).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top