-_-#【Backbone】Collection

时间:2023-12-30 21:19:08
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="../../app-min.css">
</head>
<body>
<script src="../../jquery/jquery-1.10.2.js"></script>
<script src="../underscore.js"></script>
<script src="../backbone.js"></script>
<script>
var Book = Backbone.Model.extend({
defaults: {
title: 'default'
},
initialize: function() {
}
})
var BookShelf = Backbone.Collection.extend({
model: Book
})
var book1 = new Book({title: 'book1'})
var book2 = new Book({title: 'book2'})
var book3 = new Book({title: 'book3'})
var bookShelf = new BookShelf
bookShelf.add(book1)
bookShelf.add(book2)
bookShelf.add(book3)
bookShelf.remove(book3)
bookShelf.each(function(book) {
console.log(book.get('title'))
}) var showAllBooks = function() {
bookShelf.each(function(book) {
console.log(book.get('title'))
})
} bookShelf.bind('reset', showAllBooks)
bookShelf.url = '/books/'
bookShelf.fetch({
reset: true,
success: function(collection, response, options) {
collection.each(function(book) {
console.log(book.get('title'))
})
},
error: function(collection, response, options) {
console.log('error')
}
}) var NewBooks = Backbone.Collection.extend({
model: Book,
url: '/books/'
})
var books = new NewBooks
var onebook = books.create({
title: "I'm coming"
})
</script>
<article class="content">
<pre>var Book = Backbone.Model.extend({
defaults: {
title: 'default'
},
initialize: function() {
}
})
var BookShelf = Backbone.Collection.extend({
model: Book
})
var book1 = new Book({title: 'book1'})
var book2 = new Book({title: 'book2'})
var book3 = new Book({title: 'book3'})
var bookShelf = new BookShelf
bookShelf.add(book1)
bookShelf.add(book2)
bookShelf.add(book3)
bookShelf.remove(book3)
bookShelf.each(function(book) {
console.log(book.get('title'))
}) var showAllBooks = function() {
bookShelf.each(function(book) {
console.log(book.get('title'))
})
} bookShelf.bind('reset', showAllBooks)
bookShelf.url = '/books/'
bookShelf.fetch({
reset: true,
success: function(collection, response, options) {
collection.each(function(book) {
console.log(book.get('title'))
})
},
error: function(collection, response, options) {
console.log('error')
}
}) var NewBooks = Backbone.Collection.extend({
model: Book,
url: '/books/'
})
var books = new NewBooks
var onebook = books.create({
title: "I'm coming"
})</pre>
</article>
</body>
</html>