在渲染集合视图时设置模型

时间:2016-02-17 15:33:19

标签: backbone.js backbone-collections

我创建了一个用户集合,并为其提供了一个URL来获取用户列表。但是当我尝试将整个集合与各个模型视图一起渲染时,模型不会被分配从集合URL中获取的值。

// Backbone Collection View
app.UserCollectionView = Backbone.View.extend({
el: '#users-list',

template: _.template($('#connections-template').html()),

initialize: function() {
    this.connections = new app.UserCollection();
    var self = this;
    this.connections.fetch().done(function() {
        self.render();
    });
},

render: function() {
    this.$el.html(this.template());
    // this.$el.append( this.template( this.model.toJSON()));
    this.connections.each(function(user) {


        console.log('User : ' + user.get('name'));  
        // This prints only the default name all the time. (14 times)


        var userView = new app.UserView({
            model: user
        });
        // userView.model.fetch();
        userView.render();
    });
}

});

调用render时,connections.each正好迭代14次(响应JSON中的用户数),但未分配模型的属性;它仅使用默认值。我在这里做错了什么?

以下是文件的完整内容:http://pastebin.com/xD4LyK9N

更新

这是来自服务器的JSON响应:http://pastebin.com/S4HH1wUD 这是HTML模板:http://pastebin.com/v7kfBJ4Y

1 个答案:

答案 0 :(得分:1)

检查解析函数中返回的数据,它似乎不正确或无效。您可以从解析函数发布console.log输出,这将有助于调试问题。 我绕过了fetch函数并直接分配了json数据,它工作正常。



var root = '';
var app = {};

var data = {
    "data": [
        {
            "cities": {
                "current_city": {
                    "colleges_count": 0,
                    "token": 1630,
                    "uid": "thoothukudi",
                    "colleges": [],
                    "name": "Thoothukudi",
                    "state": {
                        "name": "Tamil Nadu",
                        "token": 1033,
                        "uid": "tamil_nadu"
                    }
                },
                "native_city": {
                    "colleges_count": 0,
                    "token": 1630,
                    "uid": "thoothukudi",
                    "colleges": [],
                    "name": "Thoothukudi",
                    "state": {
                        "name": "Tamil Nadu",
                        "token": 1033,
                        "uid": "tamil_nadu"
                    }
                }
            },
            "college": null,
            "sex": null,
            "account_type": "user",
            "token": 1001,
            "about_me": null,
            "confirmation_token": "",
            "name": "Admin",
            "status": "verified",
            "email": "admin@domain.tld",
            "website": null,
            "dob": null,
            "passion": {
                "parent": {
                    "type": "category",
                    "uid": "music"
                },
                "description": null,
                "token": 1002,
                "uid": "singing",
                "name": "Singing",
                "person": "Singer",
                "type": "passion"
            },
            "username": "admin"
        },
        {
            "cities": {
                "current_city": {
                    "colleges_count": 0,
                    "token": 1630,
                    "uid": "thoothukudi",
                    "colleges": [],
                    "name": "Thoothukudi",
                    "state": {
                        "name": "Tamil Nadu",
                        "token": 1033,
                        "uid": "tamil_nadu"
                    }
                },
                "native_city": {
                    "colleges_count": 0,
                    "token": 1630,
                    "uid": "thoothukudi",
                    "colleges": [],
                    "name": "Thoothukudi",
                    "state": {
                        "name": "Tamil Nadu",
                        "token": 1033,
                        "uid": "tamil_nadu"
                    }
                }
            },
            "college": null,
            "sex": null,
            "account_type": "user",
            "token": 1004,
            "about_me": null,
            "confirmation_token": "",
            "name": "Justin Kricket",
            "status": "verified",
            "email": "justin@domain.tld",
            "website": null,
            "dob": null,
            "passion": {
                "parent": {
                    "type": "category",
                    "uid": "music"
                },
                "description": null,
                "token": 1002,
                "uid": "singing",
                "name": "Singing",
                "person": "Singer",
                "type": "passion"
            },
            "username": "justin"
        },
        {
            "cities": {
                "current_city": {
                    "colleges_count": 0,
                    "token": 1630,
                    "uid": "thoothukudi",
                    "colleges": [],
                    "name": "Thoothukudi",
                    "state": {
                        "name": "Tamil Nadu",
                        "token": 1033,
                        "uid": "tamil_nadu"
                    }
                },
                "native_city": {
                    "colleges_count": 0,
                    "token": 1630,
                    "uid": "thoothukudi",
                    "colleges": [],
                    "name": "Thoothukudi",
                    "state": {
                        "name": "Tamil Nadu",
                        "token": 1033,
                        "uid": "tamil_nadu"
                    }
                }
            },
            "college": null,
            "sex": null,
            "account_type": "user",
            "token": 1007,
            "about_me": null,
            "confirmation_token": "",
            "name": "Karti Mako",
            "status": "verified",
            "email": "karti@domain.tld",
            "website": null,
            "dob": null,
            "passion": {
                "parent": {
                    "type": "category",
                    "uid": "music"
                },
                "description": null,
                "token": 1002,
                "uid": "singing",
                "name": "Singing",
                "person": "Singer",
                "type": "passion"
            },
            "username": "karti"
        },
        {
            "cities": {
                "current_city": {
                    "colleges_count": 0,
                    "token": 1630,
                    "uid": "thoothukudi",
                    "colleges": [],
                    "name": "Thoothukudi",
                    "state": {
                        "name": "Tamil Nadu",
                        "token": 1033,
                        "uid": "tamil_nadu"
                    }
                },
                "native_city": {
                    "colleges_count": 0,
                    "token": 1630,
                    "uid": "thoothukudi",
                    "colleges": [],
                    "name": "Thoothukudi",
                    "state": {
                        "name": "Tamil Nadu",
                        "token": 1033,
                        "uid": "tamil_nadu"
                    }
                }
            },
            "college": null,
            "sex": null,
            "account_type": "user",
            "token": 1010,
            "about_me": null,
            "confirmation_token": "",
            "name": "Laurel R K",
            "status": "verified",
            "email": "laurel@domain.tld",
            "website": null,
            "dob": null,
            "passion": {
                "parent": {
                    "type": "category",
                    "uid": "music"
                },
                "description": null,
                "token": 1002,
                "uid": "singing",
                "name": "Singing",
                "person": "Singer",
                "type": "passion"
            },
            "username": "laurel"
        },
        {
            "cities": {
                "current_city": {
                    "colleges_count": 0,
                    "token": 1630,
                    "uid": "thoothukudi",
                    "colleges": [],
                    "name": "Thoothukudi",
                    "state": {
                        "name": "Tamil Nadu",
                        "token": 1033,
                        "uid": "tamil_nadu"
                    }
                },
                "native_city": {
                    "colleges_count": 0,
                    "token": 1630,
                    "uid": "thoothukudi",
                    "colleges": [],
                    "name": "Thoothukudi",
                    "state": {
                        "name": "Tamil Nadu",
                        "token": 1033,
                        "uid": "tamil_nadu"
                    }
                }
            },
            "college": null,
            "sex": null,
            "account_type": "user",
            "token": 1013,
            "about_me": null,
            "confirmation_token": "",
            "name": "Rocky Bossy",
            "status": "verified",
            "email": "rocky@domain.tld",
            "website": null,
            "dob": null,
            "passion": {
                "parent": {
                    "type": "category",
                    "uid": "music"
                },
                "description": null,
                "token": 1002,
                "uid": "singing",
                "name": "Singing",
                "person": "Singer",
                "type": "passion"
            },
            "username": "rocky"
        },
    ],
    "status": "success",
    "http_status": 200,
    "message": null
}


// Backbone Model
app.UserModel = Backbone.Model.extend({
    defaults: {
        // urlRoot: root + '/users',
        name: 'Default Name',
        email: '30',
        username: 'default_username'
    },

    initialize: function() {
        // this.fetch();
        // console.log('User model \'' + this.id + '\' has been initialized.');
    },
});

// Backbone Model View
app.UserView = Backbone.View.extend({
    el: '#users-list',
    // el: '.user-box-wrapper',

    template: _.template($('#connections-user-template').html()),

    initialize: function() {
        // this.render();
    },

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

// Backbone Collection
app.UserCollection = Backbone.Collection.extend({
    model: app.UserModel,
    url: root ,

    initialize: function() {
    		
        // this.fetch();
    },

    parse: function(d) {
    		console.log(data.data)
        return data.data;
    }
});

// Backbone Collection View
app.UserCollectionView = Backbone.View.extend({
    el: '#users-list',

    template: _.template($('#connections-template').html()),

    initialize: function() {
        this.connections = new app.UserCollection(data.data);
        var self = this;
        self.render();
        //this.connections.fetch().done(function() {
        //    self.render();
        //});
    },

    render: function() {
        this.$el.html(this.template());
        // this.$el.append( this.template( this.model.toJSON()));
        this.connections.each(function(user) {
            console.log('User : ' + user.get('name'));
            var userView = new app.UserView({
                model: user
            });
            // userView.model.fetch();
            userView.render();
        });
    }
});
var connectionsView = new app.UserCollectionView();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.3/backbone-min.js"></script>
<body>

    <header id="top">
      <div id="logo-wrapper">
        <img src="../static/img/logo.png" alt="Logo" id="logo">
      </div>
      <div id="top-links">
        <div id="top-profile-box" class="toplink">
          <div id="top-profile-data-box">
            <div id="top-profile-data-name">Kevin Isaac</div>
            <div id="top-profile-data-passion">Writer</div>
          </div>
          <img id="top-profile-image" src="../static/img/user1.jpg" alt="">
        </div>
        <div id="notification-icon" class="toplink"></div>
        <div id="top-message-icon" class="toplink"></div>
        <div id="logout-icon" class="toplink"></div>
      </div>
    </header>
    <div id="middle">
      <nav id="side-nav">
        <div id="side-nav-top">
          <div class="side-nav-link" id="side-nav-home-link">
            <div class="side-nav-link-img"></div>
            <div class="side-nav-link-title">Home</div>
          </div>
          <div class="side-nav-link" id="side-nav-profile-link">
            <div class="side-nav-link-img"></div>
            <div class="side-nav-link-title">Profile</div>
          </div>
          <div class="side-nav-link" id="side-nav-messages-link">
            <div class="side-nav-link-img"></div>
            <div class="side-nav-link-title">Message</div>
          </div>
          <div class="side-nav-link" id="side-nav-account-link">
            <div class="side-nav-link-img"></div>
            <div class="side-nav-link-title">Account</div>
          </div>
        </div>
      </nav>
      <div id="main-content">
        <!-- Start of page specific HTML -->

        <div id="content-title">
          <div class="content-subtitle">Connections</div>
          <div class="content-subtitle">Followers</div>
          <div class="content-subtitle">Followings</div>
        </div>

        <div id="content-body">
          <div id="users-box">
            <div id="users-list">No connection</div>
              <!-- Backbone Template Starts --> 
              <script type="text/template" id="connections-template"></script>
              <script type="text/template" id="connections-user-template">
                <div class="user-box-wrapper">
                  <div class="user-box">
                    <div class="user-pic-wrapper">
                      <img src="/static/img/user1.jpg" alt="">
                    </div>
                    <div class="user-data" id="boox">
                      <div class="user-name"><%= name %></div>
                      <div class="user-passion"><%= username %></div>
                      <div class="user-city"><%= email %></div>
                    </div>
                  </div>
                </div>
              </script>
              <!-- Backbone Template Ends --> 


            <div id="users-side-box">
              <div id="users-box-search">
                <input id="user-search" type="text" name="">
              </div>
              <div id="user-metadata">
                <div id="metadata-user-top-box">
                  <div id="metadata-user-image-wrapper">
                    <img src="/static/img/user1.jpg" alt="">
                  </div>
                  <div id="metadata-user-name-box">
                    <div id="metadata-name">Name's Bond</div>
                    <div id="metadata-passion">Assassin</div>
                  </div>
                </div>
                <div id="metadata-user-bottom-box">
                  <div class="metadata-user-attribute">
                    <span class="metadata-property">Studied at: </span>
                    <span class="metadata-value">Karunya University </span>
                  </div>
                  <div class="metadata-user-attribute">
                    <span class="metadata-property">Native City: </span>
                    <span class="metadata-value">London</span>
                  </div>
                  <div class="metadata-user-attribute">
                    <span class="metadata-property">Website: </span>
                    <span class="metadata-value">www.007.com</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- End of page specific HTML -->
      </div>
      <aside id="main-aside">
        Aside one two therr
      </aside>
    </div>

    
  </body>
&#13;
&#13;
&#13;

https://jsfiddle.net/akramparvez/a2jvh3mk/