简单事件backbone.js错误

Simple events backbone.js error

本文关键字:错误 js backbone 事件 简单      更新时间:2023-09-26

在index.html上运行此操作时,我得到以下错误:"UnaughtSyntaxError:意外令牌:",指的是

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

具体是指":"此处"点击#添加好友":"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);

末尾有一个额外的逗号:

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

在初始化方法的末尾,您还缺少一个关闭的}

initialize: function () {
    this.friends = new Friends(null, {view: this});
}, // add a "}," here
events: {
   "click #add-friend": "showPrompt"
},

您的"initialize"函数缺少"}"。如果没有这一点,它就会认为令牌"events"正在启动一个新的语句。直到字符串常量后面的冒号都是好的,这在上下文中是语法错误的。

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

删除属性值后的逗号:

events: {
     "click #add-friend": "showPrompt" // <-- comma removed!
},