2

我对 Backbone.js 非常陌生,并且一直在遵循一些教程来编写下面的脚本。我想要实现的是在使用我的路由时从休息 api 中检索 JSON 数据。如果您查看朋友路线的人员功能,您可以看到我的目标。我哪里错了?

<!DOCTYPE html>
<html>
<head>
    <title>I have a back bone</title>
</head>
<body>
    <button id="add-friend">Add Friend</button>
    <ul id="friends-list">
    </ul>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
<script>
Friend = Backbone.Model.extend({
    name: null,
    age: null,
});
FriendDetailModel = Backbone.Model.extend();
FriendDetailCollection = Backbone.Collection.extend({
    url: 'slim/index.php/friends/',
    model: FriendDetailModel

});

Friends = Backbone.Collection.extend({
    initialize: function(models, options) {
        this.bind("add",options.view.addFriendLi);
    }
});
AppView = Backbone.View.extend({
    el: $("body"),
    initialize: function() {
        this.friends= new Friends(null, {view:this});
    },
    events: {
        "click #add-friend":  "showPrompt",
    },
    showPrompt: function () {
        var friend_name = prompt("Who is your friend?");
        var friend_age = prompt("What is your friends age?");
        var friend_model = new Friend({name: friend_name, age: friend_age});

        this.friends.add(friend_model);
    },
    addFriendLi: function(model) {
        $("#friends-list").append("<li>" + model.get('name') + " " + model.get('age') + "</li>");
    }
});
var appview = new AppView;

AppRouter = Backbone.Router.extend({
    routes: {
        "friends":"people",
        "person/:name":"personDetail"
    },

    people: function() {
        console.log('all the people');
        var people = new FriendDetailCollection;
            people.fetch({
                    success: function(data) {
                            console.log(data);
                    }

    },

    personDetail: function(name) {
        console.log('one person named ' + name);
    }
});

var approuter = new AppRouter;
Backbone.history.start();
</script>
</body>
</html>

运行 people.fetch Console.log 后显示

d
_byCid: Object
_byId: Object
length: 4
models: Array[4]
__proto__: x

如果我做 console.log(data.toJSON()); 它返回

[]
4

1 回答 1

3

我最终通过执行以下操作解决了问题:

我在路由器之外创建了一个新集合:

var people = new FriendDetailCollection;

当我创建视图时,我指定了我之前创建的集合。

friendview = new FriendView({collection: people});

我的 FriendView 中有错字。以前我有 _.bind(this, 'render')。它需要是

_.bindAll(this,'render');

此外,我将 console.log 放在 FriendView 中的 render() 函数中。

FriendView = Backbone.View.extend({
        el: $("body"),
        initialize: function() {
                _.bindAll(this,'render');
                this.collection.bind('reset', this.render);
        },
        render: function() {
                console.log(this.collection.toJSON());
        }

});
于 2012-09-01T15:58:04.930 回答