在.fetch()之后,BackboneJS .get()和.at()未定义

时间:2014-03-12 04:27:06

标签: backbone.js collections get undefined

本地主机:3000

[{"idrooms":1,"roomname":"red","occupants":0},    {"idrooms":2,"roomname":"green","occupants":0},{"idrooms":3,"roomname":"blue","occupants":0},   {"idrooms":4,"roomname":"yellow","occupants":0},    {"idrooms":5,"roomname":"purple","occupants":0},{"idrooms":6,"roomname":"cyan","occupants":0}]

在客户端,我从目前为止所知的基础知识入手:                                                                                             标题                                  

            <script src="jslib/jquery.js"></script>
            <script src="jslib/underscore.js"></script>
            <script src="jslib/backbone.js"></script>
            <script>
            // Your code goes here
            var Room = Backbone.Model.extend({
                defaults: {
                idrooms: 0,
                roomname: "default",
                occupants: 0
                }
            });

            var RoomList = Backbone.Collection.extend({
                model: Room,
                url: 'http://localhost:3000'
            });

            var roomlist = new RoomList();
            roomlist.fetch();

            console.log(roomlist);
            console.log(roomlist.at(1));
            console.log(roomlist.get(1));
            </script>
            </body>
            </html>

房间清单中有各种类型的数据,如果我钻进它,我会看到所有六个房间模型对象的属性。 roomlist.at(1)和roomlist.get(1)返回一个未定义的。也许我在某个地方犯了错误。

服务器很短也许我应该发布它:

            var express = require('express')
              , cors = require('cors')
              , get = require('./routes/get')
              , http = require('http')
              , path = require('path')
              , mysql = require('mysql')
              , app = express();

            var connection = mysql.createConnection({ host: 'localhost', user: 'root',  
                                                      password: 'oilwell123', database: 'multiroomchat'});

            app.get('/', cors(), function(req, res, next){
                if (connection) {
                    connection.query('select * from rooms', function(err, rows, fields) {
                        if (err) throw err;
                        res.contentType('application/json');
                        //res.write(JSON.stringify(rows));
                        res.send(rows);
                        res.end();
                    });
                }
            });

            app.listen(3000, function(){
              console.log('CORS-enabled web server listening on port 80');
            });

jsonlint说它有效的json ......

感谢您发帖...

1 个答案:

答案 0 :(得分:2)

fetch方法是异步的,因此在您使用它时不会分配输出变量。

试试这个。

roomlist.fetch({
    success : function(collection, respone) {
        console.log(collection);
        console.log("collection.at(1)", collection.at(1));
        console.log("collection.get(c0)", collection.get("c0"));        
    }
});