0

在 index.html 上运行它时,我收到以下错误:“Uncaught SyntaxError: Unexpected token :”,指

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

此处特指“:”“点击#add-friend”:“showPrompt”,更多上下文如下。任何意见,将不胜感激。

(function ($) {

    Friend = Backbone.Model.extend({
        // create a model to to hold friend attribute
        name: null
    });

    Friends = Backbone.Collection.extend({
        // this is our friends collection and holds out Friend models
        initialize: function(models, options) {
            this.bind("add", options.view.addFriendLi);
            // listens for "add" and calls a view function if so
        }
    });

    AppView = Backbone.View.extend({
        el: $("body"),
        initialize: function () {
            this.friends = new Friends(null, {view: this});
        // creates a new friends collection when the view is initialized
        // pass it a reference to the view to create a connection between the two
        events: {
            "click #add-friend": "showPrompt"
        },
        showPrompt: function () {
            var friend_name = prompt("Who is your friend?");
            var friend_model = new Friend({name:friend_name});
            // adds a new friend model to out Friend collection
            this.friends.add(friend_model);
        },
        addFriendLi: function (model) {
            // the parameter passed is a reference to the model that was added
            $("#friends_list").append("<li>" + model.get('name') + "</li>");
        }
    });
    var appview = new AppView;
})(jQuery);
4

3 回答 3

2

最后有一个额外的逗号:

"click #add-friend": "showPrompt" // remove the comma

您还缺少}初始化方法末尾的关闭:

initialize: function () {
    this.friends = new Friends(null, {view: this});
}, // add a "}," here

events: {
   "click #add-friend": "showPrompt"
},
于 2012-03-23T15:45:21.900 回答
2

您的“初始化”功能缺少“}”。没有它,它认为令牌“事件”正在开始一个新的声明。直到字符串常量后面的冒号为止,这一切都很好,在这种情况下,这在语法上是不正确的。

哦,你还需要一个逗号,将“initialize”属性的值与“events”属性分开。

于 2012-03-23T15:45:30.867 回答
1

去掉属性值后面的逗号:

events: {
     "click #add-friend": "showPrompt" // <-- comma removed!
},
于 2012-03-23T15:45:20.683 回答