gpt4 book ai didi

javascript - 将模型添加到集合会引发错误 "Uncaught TypeError: Cannot read property ' idAttribute' of undefined"

转载 作者:行者123 更新时间:2023-11-29 23:45:12 25 4
gpt4 key购买 nike

我在尝试将多个模型从服务器添加到集合时遇到错误。它抛出错误:

Uncaught TypeError: Cannot read property 'idAttribute' of undefined

这是一个给出相同错误的测试示例:

<script type="text/javascript" src="js/jquery.3.2.1.min.js"></script>
<script type="text/javascript" src="js/underscore.1.8.3.min.js"></script>
<script type="text/javascript" src="js/backbone.1.3.3.min.js"></script>

<script type="text/javascript">

var Mymodel = Backbone.Model.extend({
defaults:{
id: null,
},
idAttributes: "id",
render: function(){
collection.add([{id:1, name: "name"},{id:2, name: "name"}])
}
});

mymodel = new Mymodel();

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

collection = new mycollection();

mymodel.render();

</script>

最佳答案

model property集合类的应该是模型构造函数,而不是实例。

Backbone.Collection.extend({ model: Mymodel });

模型类有一个 idAttribute property ,单数,默认情况下已经是 'id'


id 属性放在 defaults 中不是必需的,并且可能会导致问题出现。


除了前面几点,在模型中进行渲染是不好的做法。使用view为此。

render: function(){
collection.add([{ id:1, name: "name" }, { id:2, name: "name" }])
}

我知道这是一个测试示例,但如果不是,模型 不应更改全局集合实例。类的全部意义在于将责任范围限定在类本身,而不是类之外。

使用这样的全局变量与使用 Backbone 的全部要点背道而驰。

需要最少的代码

var MyModel = Backbone.Model.extend({}),
MyCollection = Backbone.Collection.extend({ model: MyModel }),
collection = new MyCollection();

collection.add([
{ id: 1, name: "name" },
{ id: 2, name: "name" }
]);

关于javascript - 将模型添加到集合会引发错误 "Uncaught TypeError: Cannot read property ' idAttribute' of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44417777/

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