Olivier
Olivier

Reputation: 3471

How to handle nested views with Backbone.js?

In my app i have a few tagList, each one contains a few tags grouped by index_name.

I'm lost on how should i handle that with Backbone views.

I have a TagListView that extends Backbone.View, i guess i'll handle all events with this view.

My main question i : should i create a TagView with a render function that would be created & rendered for each tag in the TagListView render function ?


Here is what i do so far in my view : (is this ok for initialization ?!)

    <ul id="strategy-tags">
        <!-- initial data -->
        <script type="text/javascript">
            AppData.strategyTagList = $.parseJSON('<?php echo json_encode($strategyTagList); ?>');
            strategyTagListView = new App.TagListView({el : "#strategy-tags", data: AppData.strategyTagList});
        </script>
    </ul>

Inside my core.js :

    App.TagListView = Backbone.View.extend({

        // dom event specific to this item.
        events: {
        },

        initialize: function(options) {
            this.el = options.el;
        },

        render: function() {
            // let's construct the tag list from input data
            _.each(options.data, function(index) {
                // render index? <-- how ?
                _.each(index, function(tag) {
                    // render tag? <-- how ?
                    console.log(tag);
                });
            });
            return this;
        }

    });

Thanks a lot.

Upvotes: 2

Views: 3162

Answers (2)

34m0
34m0

Reputation: 5955

It seems to be a question of granularity here, and one I've asked myself on occasion. My advice would be not to over do the views. It is akin to creating objects for everything in java - sometimes a simple string will suffice. If you find a case of increased granularity in the future you can always come back and change it.

Upvotes: 2

isNaN1247
isNaN1247

Reputation: 18109

I would say yes, the benefit of the individual 'item' view being able to re-render individually is that if you make changes to the model behind such an item, only that item will need to be re-rendered by the browser. Which is best for performance.

Upvotes: 4

Related Questions