Domanda

i am just writing a simple backbone program. But i am unsure what i am doing wrong when pushing the JSON data to the underscore template. Any help is appreciated.

My code looks like this:

    <!doctype html>
    <html>
       <head>
          <title>Backbone tutorial</title>
       </head>
       <body>
          <div class="user">user</div>
          <div class="page"></div>

          <script type="text/template" id="user-list-template">
            <h1> <%= data.key %> </h1>

          </script>

          <script type="text/javascript" src="jquery.js"></script>
          <script type="text/javascript" src="underscore.js"></script>
          <script type="text/javascript" src="backbone.js"></script>
          <script>

This is my Collection code

              var Album = Backbone.Collection.extend({

                url : "/data.json"
              });

This is my view code

             var UserList= Backbone.View.extend({
                el:'.page',
                template:_.template($('#user-list-template').html()),
                render : function(){
                    var that=this;
                    var album= new Album();
                    album.fetch({
                        success:function(album){

                            var _data = {data : album.models} ;

                            $(that.el).html(that.template(_data));
                        }
                    })


                }

             });

This is my Router code

             var Router = Backbone.Router.extend({
                routes: {
                    "":                 "home"   // #help
                }


             });



             var userList= new UserList();
             var router = new Router();

             router.on('route:home', function(){
                userList.render();
             });

             Backbone.history.start();
          </script>
       </body>
    </html>

and here is the data.json file

{ "key" : "value to print on template "}
È stato utile?

Soluzione

There're plenty of problems here. First, the Collection should consist of Models, which you specify by the model while creating the collection. Second, the success callback returns the data received, not the collection. Third, it's a bad idea to do AJAX in the render call.

What you should do, ideally is the following:

  1. Instantiate the model or collection
  2. Provide it to the view
  3. Listen to events on the model/collection, e.g. (this.listenTo(this.collection, 'sync', this.render)
  4. Fetch the collection. The fetching can be done in the router in your example.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top