我不跟。 模型如何定义为函数?
我昨天实际上遇到了这个问题(或类似的问题)。
您可以在集合上定义模型函数以创建多态模型。
在集合上调用.add
时,Backbone 代码会尝试在model
属性上调用.prototype.idAttribute
,但如果您已将model
函数定义为ES2015 类方法则没有prototype
属性。
见这里: https ://github.com/jashkenas/backbone/blob/75e6d0ce6394bd2b809823c7f7dc014ddb6ae287/backbone.js#L1102
因此,例如,这将导致问题:
const Library = Backbone.Collection.extend({
model () {
// stuff goes here
}
});
如果你这样指定它,那么问题就消失了:
const Library = Backbone.Collection.extend({
model: function () {
// stuff goes here
}
});
我昨天实际上遇到了这个问题(或类似的问题)。
您可以在集合上定义模型函数以创建多态模型。
在集合上调用
.add
时,Backbone 代码会尝试在model
属性上调用.prototype.idAttribute
,但如果您已将model
函数定义为ES2015 类方法则没有prototype
属性。看这里:
因此,例如,这将导致问题:
const Library = Backbone.Collection.extend({ model () { // stuff goes here } });
如果你这样指定它,那么问题就消失了:
const Library = Backbone.Collection.extend({ model: function () { // stuff goes here } });
谢谢问题详细描述!
但是您的答案不是解决 idAttribute 的问题。
添加新模型参考未添加。 因此,您无法通过 id 获得新模型。
Workarond - 添加了与模型相同的 model.prototype.idAttribute。
我认为问题在于 $# Collection
model
定义为: Override this property to specify the model class that the collection contains.
此 API 不支持将模型定义为函数。
@paulfalgout Collection.model的主干文档指定您可以将函数设置为model
。 使用model ()
语法(而不是model: function()
)不可能做到这一点,这对我来说似乎是一个错误,或者至少非常令人困惑。
是的,我在原始消息中链接到文档的相关部分。
见这里: https: //backbonejs.org/#Collection -model
@PavelKoroteev :看起来我们的问题是相关的,但不一样。
这就是我所说的(从控制台粘贴):
collection = new (Backbone.Collection.extend({ model (attrs, options) { return new (Backbone.Model.extend({ idAttribute: 'customId' }))(attrs, options)}}));
child {length: 0, models: Array(0), _byId: {…}}
collection.add({ customId: 'id.1' });
backbone.js:1102 Uncaught TypeError: Cannot read property 'idAttribute' of undefined
at child.modelId (backbone.js:1102)
at child.get (backbone.js:997)
at child.set (backbone.js:872)
at child.add (backbone.js:814)
at <anonymous>:1:12
我认为这个问题实际上是一样的。 也和https://github.com/jashkenas/backbone/issues/4203一样
使用model: function(attrs, options)
会创建一个没有idAttribute
的原型,它会回退到id
所以它会“工作”
您是正确的,多态模型已记录在案。 _but_... 它不支持idAttribute
或 es6 类型的方法,因为这条线与model.prototype
有一段时间了。
看到 2016 年的 PR 萎靡不振并且没有被合并(或被拒绝以支持更好的东西)基本上阻止了我甚至试图通过 PR 来解决这个问题。
据我所知,Backbone 几乎已经死了。
和其他人一样,我创建了一个 fork,我的称为Skeletor ,我将使用它来将我的 Backbone 代码更新为更现代的 API 和标准,然后我将逐渐转向更好的东西。
在解决冲突后,我刚刚合并了旧的https://github.com/jashkenas/backbone/pull/3966 PR。 让我知道它是否给您带来任何麻烦...
最有用的评论
在解决冲突后,我刚刚合并了旧的https://github.com/jashkenas/backbone/pull/3966 PR。 让我知道它是否给您带来任何麻烦...