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

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

问题描述

在骨干JS集合不允许你设置属性,但我常常发现,有需要存储关于收集一些元信息。哪里是设置信息的最好地方?

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?

推荐答案

这也可能是最好的究竟是预期的方式使用宝典:作为模特捆绑。 (朱利安已经评论这个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)

假设你正在为骨干的文档例子思考书(模型)的库(集合)的。这是有道理的,你有哪些要存储,想去哪这本书库所在的地址库的元信息。

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
};

在这个例子中,我定义库作为一个普通的JavaScript对象。很明显,你也可以让图书馆是一个模型,使之具有所有的骨干花俏。
在这里我想说的是,你需要采取退一步,看到重新present现实更现实的方式,要分配给收集额外的属性是在一个对象一涨水平的事实,兄弟属性:图书馆在这种情况下。

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天全站免登陆