试图从backbone.js中的视图调用集合中的方法

时间:2012-06-11 13:05:49

标签: backbone.js

我刚刚开始使用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;
}); 

1 个答案:

答案 0 :(得分:3)

您在initialize中拼错了FriendCollection,因此您永远不会将该集合实际绑定到传入的视图中。

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