gpt4 book ai didi

javascript - 主干从模型与集合中获取数据

转载 作者:行者123 更新时间:2023-11-30 00:22:15 24 4
gpt4 key购买 nike

我创建了一个简单的主干项目,它在其中获取所有书籍的详细信息并在 UI 中显示。我正在从模型中获取所有书籍的详细信息。根本不使用像这样的集合

var BookModel= Backbone.Model.extend({
initialize: function(){
this.fetchData();
},

fetchData: function(){
this.url= "/get/all_books";

this.fetch({
success: success_callback,
error: error_callback
})
}
});

这工作正常。但为什么我必须使用 collections ?如果我使用集合,它会像下面这样

var BookModel= Backbone.Model.extend({
defaults:{
id:'',
name: '',
author: ''
}
});


var BookCollection= Backbone.Collection.extend({
model: BookModel,

initialize: function(){
this.fetchData();
},

fetchData: function(){
this.url= "/get/all_books";

this.fetch({
success: success_callback,
error: error_callback
})
}
});

同样的效果。我不明白为什么要在我的案例中使用 Collections。请用我的示例帮助我理解这个概念,为什么我必须在这里使用集合。我用 Google 搜索了很多,找到了最佳答案。

谢谢

最佳答案

假设您有两条 2 条路线:

/books
/books/:id

现在要获取特定书籍,您可以向 /book/:id 路由发送请求,其中 :idid这本书。

GET /books/1
< { id: 1, title: 'On the Genealogy of Morality', ... }

现在如果你想得到所有的书会怎样?您向 /books 路由发送请求。

GET /books
< [{ id: 1, title: '...', ... }, { id: 2, title: '...', ... }, ...]

Backbone 遵循同样的原则。单本书的模型。许多书籍的收藏。当您使用集合时,Backbone 会为每本书创建一个模型。为多个项目使用一个模型是错误的。

You said "Backbone creates one Model for each book.". at what step it creates?

它在 sync 事件上创建模型,即当获取所有项目的请求完成时。

...how does it helps me. In my case I always fetch all books, not single book.

Backbone 集合总是使用 Backbone 模型。如果您没有显式设置 Collectionmodel 属性,Backbone 将使用普通模型,即 Collection 的 model 属性应该始终引用模型。

// https://github.com/jashkenas/backbone/blob/master/backbone.js#L782

// Define the Collection's inheritable methods.
_.extend(Collection.prototype, Events, {

// The default model for a collection is just a **Backbone.Model**.
// This should be overridden in most cases.
model: Model,

将模型视为对象,将集合视为对象数组

关于javascript - 主干从模型与集合中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32706917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com