没有方法’获得’骨干模型保存
我正在使用骨干来制作一个相当复杂的forms。 我有许多嵌套模型,并且一直在计算父模型中的其他变量,如下所示:
// INSIDE PARENT MODEL computedValue: function () { var value = this.get('childModel').get('childModelProperty'); return value; }
这似乎可以很好地保持我的UI同步,但一旦我打电话
.save()
在父模型上,我得到:
Uncaught TypeError: Object # has no method 'get'
似乎儿童模型暂时停止响应。
我在做一些内在错误的事情吗?
编辑:堆栈跟踪是:
Uncaught TypeError: Object # has no method 'get' publish.js:90 Backbone.Model.extend.neutralDivisionComputer publish.js:90 Backbone.Model.extend.setNeutralComputed publish.js:39 Backbone.Events.trigger backbone.js:163 _.extend.change backbone.js:473 _.extend.set backbone.js:314 _.extend.save.options.success backbone.js:385 f.Callbacks.o jquery.min.js:2 f.Callbacks.p.fireWith jquery.min.js:2 w jquery.min.js:4 f.support.ajax.f.ajaxTransport.send.d
编辑#2以回应以下评论:
有一些基本的我还没有得到。 我替换了对this.get(’childModel’)[‘childModelProperty’]的一些引用,现在我得到了’无法读取未定义的属性childModelProperty’。
我还没有从服务器中提取任何东西,父模型就是这样创建的
define(['jquery', 'underscore', 'backbone', 'models/childmodel'], function($, _, Backbone, ChildModel) { var ParentModel = Backbone.Model.extend({ defaults: { childModel : new ChildModel() }
defaults
仅在您创建模型时使用。 在调用save之后,它将调用set
,它将用一个简单的javascript对象覆盖childModel。 在我看来,你有几个选择:
1)使用Backbone.Relational
2)在每个父模型中set
覆盖以更新现有子模型(或创建它),如下所示:
children:{ childModel: ChildModel } set: function (key, value, options) { var attrs; if (_.isObject(key) || key == null) { attrs = key; options = value; } else { attrs = {}; attrs[key] = value; } _.each(this.children, function (childType, name) { if (!attrs.hasOwnProperty(name)) return; //assume the child is just a model--not a collection var newValue = attrs[name]; delete attrs[name]; var isModel = this[name] && this[name].set; if (isModel && newValue) { this[name].set(newValue, options); } else if (newValue) { this[name] = new childType(newValue); } else { delete this[name]; } this.trigger('change:' + name); }, this); return Backbone.Model.prototype.set.call(this, attrs, options); }
有时你的childModel不包含Backbone.Model,就像你被分配了其他类型的对象一样。
为了避免错误,请执行此操作(并且在您的控制台中,您将获得有关该错误的childModel值的有用信息):
computedValue: function () { var value; if( this.get('childModel') instanceof Backbone.Model ){ value = this.get('childModel').get('childModelProperty'); }else{ console.log('This is weird, childModel is not a Backbone.Model', this.get('childModel') ); } return value; }