简体   繁体   中英

Backbone Json view template

I am just trying to get my head around backbone at the moment.

So i have the model, load the JSON file with the collection however i cant finger out the best way of displaying the array in the view to the underscore template.

I'm quite tired and seem to of gone through alot of tutorials, all with different ways of outputting this data through the view to the template. Is there a correct way of doing this? i'm guessing it should be looping with _.each? am i even on the correct path ? ;)

Please see code below.

Many thanks

<head>




</head>
<body>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone.js"></script>


    <script type="text/javascript">

        var News = Backbone.Model.extend();

        var Newscollection = Backbone.Collection.extend({
            model: News,
            url: 'data.js'
        });

        var NewView = Backbone.View.extend({
            el: '#News',
            template: _.template($("#NewsTemplate").html()),

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


    </script>


    <div id="News"></div>


    <script id="NewsTemplate" type="text/template">
        <%= title %>
    </script>

</body>

If you'd like to pass the collection to your template, you can do the following:

1: Define new collection in your view. Add some models to your collection. We'll define it as this.collection , and we'll assume there are multiple models in the collection by the time it gets rendered.

2: Pass the an object into the template. Make an object with 'collection' as the key and the JSON-ized collection (an array of models) as the value:

$(this.el).html(this.template({'collection': this.collection.toJSON()}));

3: Now, in the template, we can reference the collection by using <%= collection %> . However, I think you want to loop through the collection to render values. In your HTML template, you can create a loop using underscore's _.each :

    <ul>
    <% _.each(collection, function(item) { %>
        <li> <%= item.id %> : <%= item.title %> </li>
    <% }); %>
    </ul>

This will print a list of your models in the collection, assuming your models have an id and a name attribute.

Another, more 'backbone-ish' method of doing this would be to create a new view for each model in the collection, similar to the todo items in this tutorial: http://arturadib.com/hello-backbonejs/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM