简体   繁体   English

如何使用骨干.js从集合中获取模型名称

[英]How to get model name from a collection with backbone.js

How can i get model name from a collection? 如何从集合中获取型号名称? When i define a collection, i specify the model attribute as : 定义集合时,将model属性指定为:

Domains = Backbone.Collection.extend({
    model : Account
})

How can i get this attribute value? 我如何获得该属性值?

I tried Domains.model... 我尝试了Domains.model ...

First of all I don't think Backbone is gonna work if you use a String to initialize Collection.model , you have to specify a Model class reference like this: 首先,如果使用String初始化Collection.model ,我认为Backbone不会起作用,您必须指定Model类引用,如下所示:

var MyModel = Backbone.Model.extend({});

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

Said that I don't this is possible to retrieve the name of a variable from the variable reference itself. 说我不可能从变量引用本身中检索变量的名称。

I suggest to come up with a workaround which is tagging every Model with a String class attribute to which you can ask wich is the name of the class: 我建议提出一种解决方法,该方法使用String类属性标记每个Model,您可以向其询问类的名称:

var MyModel = Backbone.Model.extend({
    name: "MyModel"
});

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

var myCollection = new MyCollection();

console.log( "reference", myCollection.model ); // reference to the class 
console.log( "reference.name", myCollection.model.prototype.name );​ // string name

Check the jsFiddle 检查jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM