#database #backbone.js
Вопрос:
Как мне создать модели в URL /people
-адресе ? Я попробовал этот пример:
var John = New Person ({name: "john", age: "33"});
John.save();
Это не сохранит и всплывет с ошибкой:
Неперехваченная ошибка: необходимо указать свойство или функцию «url».
Когда я ввожу имя и возраст и нажимаю «Новый человек», это приводит к ошибкам
[HTTP/1.1 405 Метод Не разрешен.
Поэтому я застрял на создании моделей для сохранения в базе данных по URL-адресу и получении записей в базе данных. Как мне это сделать?
<!DOCTYPE html>
<head>
</head>
<body>
<div id="peopleListScope">
<ul id="allMyPeople">
</ul>
Name: <input type="text" name="name">
Age: <input type="number" name="age">
<button>New Person</button>
</div>
<script src ="jquery-3.6.0.js"></script>
<script src ="underscore-umd-min .js"></script>
<script src ="backbone-min.js"></script>
<script>
var Person = Backbone.Model.extend({
defaults: {
name: null,
age: null,
}
});
var PeopleCollection = Backbone.Collection.extend({
model: Person,
url: "/people", //the root of the RESTful route
parse: function(){
//...we may or may not need to use parse!
}
});
var peopleList = new PeopleCollection();
peopleList.fetch();
var PeopleCollectionView = Backbone.View.extend({
el: "#peopleListScope",
initialize: function(){
this.listenTo(this.collection, 'sync', this.render);
this.listenTo(this.collection, 'change', this.render);
},
render: function(){
this.collection.each(function(person){
//build the individual view for each model...
})
},
events: {
'click button':'createPerson'
},
createPerson: function(){
$name = this.$('input[name="name"]');
$age = this.$('input[name="age"]');
this.collection.create({
name: $name.val(),
age: $age.val(),
});
$name.val('');
$age.val('');
}
});
var peopleListView = new PeopleCollectionView({collection: peopleList});
</script>
</body>
</html>