Ошибка простых событий backbone.js

При выполнении этого на index.html я получаю следующую ошибку: «Uncaught SyntaxError: Unexpected token:», имея в виду

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);

person zallarak    schedule 23.03.2012    source источник


Ответы (3)


У вас есть лишняя запятая в конце:

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

Вам также не хватает закрывающего } в конце метода инициализации:

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

events: {
   "click #add-friend": "showPrompt"
},
person Didier Ghys    schedule 23.03.2012
comment
Удаление запятой не помогло. - person zallarak; 23.03.2012

Вам не хватает "}" для вашей функции "инициализации". Без этого он считает, что токен «события» начинает новый оператор. Все хорошо до двоеточия после строковой константы, что синтаксически неверно в этом контексте.

О, и вам также понадобится запятая, чтобы отделить значение свойства «инициализировать» от свойства «события».

person Pointy    schedule 23.03.2012

Удалите запятую после значения свойства:

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