在集合上设置属性 - 骨干 js [英] Setting attributes on a collection - backbone js

查看:26
本文介绍了在集合上设置属性 - 骨干 js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

backbone js 中的集合不允许你set 属性,但我经常发现需要存储一些关于集合的元信息.在哪里设置该信息的最佳位置?

Collections in backbone js don't allow you to set attributes, but I often find that there is need to store some meta-information about a collection. Where is the best place to set that information?

推荐答案

最好完全按照预期的方式使用 Collection:作为一组模型.(Julien 已经在 OP 上对此发表了评论,我想解释一下为什么我认为他是对的)

It's probably best to use Collection in exactly the way it was intended: as a bundle of models. (Julien already commented this on the OP, I'd like to give an explanation why I think he is right)

假设您正在考虑 Backbone 的文档示例中的图书(模型)的图书馆(集合).您已经获得了有关要存储的图书馆的元信息,例如该图书图书馆所在的地址,这是有道理的.

Let's say you are thinking of a Library (collection) of Book (model) as in Backbone's documentation examples. It makes sense that you've got meta information about the library which you want to store, like the address where this book library is located.

诀窍是不要将其视为元信息.您有一个拥有许多属性的图书馆,其中一个属性就是它的藏书.

The trick is not to think of it as meta information. You've got a library that has a lot of properties, and one of those properties is its collection of books.

var Book = Backbone.Model.extend({ 
    title: "Moby Dick"
});

var Collection = Backbone.Collection.extend({
    model: Book
});

var Library = {
    address: '45th Street',
    collection: Collection
};

在这个例子中,我将 Library 定义为一个普通的 JavaScript 对象.显然,您也可以使 Library 成为一个模型,以便它具有所有 Backbone 花里胡哨的功能.我的观点是,您需要通过退后一步,看到您想要分配给 Collection 的额外属性实际上是上一级对象的同级属性:在本例中为 Library,以更现实的方式表示现实.

In this example I've defined Library as a plain JavaScript object. Obviously you can also make Library be a model, so that it has all the Backbone bells and whistles. My point here is that you need to represent reality in a more realistic way by taking one step back and seeing that extra properties that you want to assign to the Collection are in fact sibling properties of an object one level up: the Library in this case.

这篇关于在集合上设置属性 - 骨干 js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆