0

我刚刚开始使用我们的backbone.js 并遵循一些简单的教程,尽管我在路上遇到了障碍。我似乎无法运行 FriendCollection.add 方法。我没有收到任何错误。我有什么遗漏吗?我相信这与 this.FriendCollection.add(friend_model) 有关。

var Friend = Backbone.Model.extend({});

var FriendCollection = Backbone.Collection.extend
({
    initalize: function(models,options)
    {
        this.bind("add", options.view.addFriendLi);
    }
});

var FriendModel = Backbone.Model.extend
({
    name:null
});

var AppView = Backbone.View.extend
({
    el:$("body"),

    initialize: function()
    {
        this.FriendCollection = new FriendCollection(null,{view:this});
    },

    events:
    {
        "click #add-friend":"showPrompt",
    },

    showPrompt: function()
    {
        var friend_name = prompt("Who is your friend?");
        var friend_model = new FriendModel({name:friend_name});
        this.FriendCollection.add(friend_model);
    },

    addFriendLi: function(model)
    {
        $("#friends-list").append("<li>"+model.get('name') + "</li>");
    },
});

$(document).ready(function() 
{
    var appview = new AppView;
}); 
4

1 回答 1

3

您拼错initialize了 in FriendCollection,因此您实际上从未将集合绑定到传入的视图。

var FriendCollection = Backbone.Collection.extend
({
    initialize: function(models,options) // Fixed here
    {
        this.bind("add", options.view.addFriendLi);
    }
});
于 2012-06-11T14:26:48.587 回答