包含集合的模型的 Backbone.js 视图?
在我的 Backbone.js 应用程序中,我有一个包含集合的模型。为了支持从后端获取该模型,我重写了解析方法,以将 JSON 响应中的数组转换为集合实例。它看起来像这样:
class SomeModel extends Backbone.Model
defaults: ->
collection: new SomeCollection([new SomeModel(attr: value)])
parse: (res) ->
res.collection = new SomeCollection(res.collection)
res
class SomeCollection extends Backbone.Collection
model: SomeOtherModel
class SomeCollectionView extends Backbone.View
el: $('collection-view')
我的问题是,虽然 SomeCollectionView
绑定到 SomeCollection
的现有实例,但在调用 SomeModel.fetch()
时实例被替换,视图不再有效。我可以在旧视图上调用 remove()
并实例化一个新视图,但我的 SomeCollectionView
位于现有 HTML 之上(不是由模板)并调用remove从DOM中取出元素。此外,我更希望我的视图能够简单地对更改事件做出反应而不是需要重建。
In my Backbone.js app I have a Model that contains a Collection. To support fetching that model from the back end I override the parse method to transform the array in the JSON response to a collection instance. It looks something like this:
class SomeModel extends Backbone.Model
defaults: ->
collection: new SomeCollection([new SomeModel(attr: value)])
parse: (res) ->
res.collection = new SomeCollection(res.collection)
res
class SomeCollection extends Backbone.Collection
model: SomeOtherModel
class SomeCollectionView extends Backbone.View
el: $('collection-view')
My problems is that while SomeCollectionView
is bound to an existing instance of SomeCollection
, when calling SomeModel.fetch()
that instance is replaced and the view is no longer valid. I could call remove()
on the old view and instantiate a new one but my SomeCollectionView
is layered on top of existing HTML (not built from a template) and calling remove pulls out the element from the DOM. Moreover, I would much prefer if my view could simply react to a change event rather than requiring reconstruction.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我从不同的“侧面”做了像你说的那样的东西(模型中的集合),这在这里可以工作。当我有一个包含集合的模型时,我使用模型中的事件来创建集合。
其余的都是一样的,所以我不会把它放进去。
另外,如果你更深入的话:
型号A->集合B ->型号B->集合C->型号C
比在构造函数中的 modelB 中,您可以创建 collectionC (前提是您不重用它)
[编辑]
我还有另一个想法:
I did stuff like you said (collection in model) from different "side" which would work here. When I had a model that had a Collection I used events in the model to create collection.
The rest is the same so I won't put it in.
Also if you go deeper:
modelA -> collecionB -> modelB -> collectionC -> modelC
Than in modelB in constructor you can create collectionC (providing you don't reuse it)
[Edit]
I've got another idea: