我有一个骨干模型(比如ModelA),我在其中定义了一组验证函数。在所有验证函数中,我将模型属性作为参数传递。在向导的每个步骤中都会调用此验证。该向导为其定义了一个模型。
validations: {
validateFuncA: function(attrs) {
//Here property1 is sometimes look like model and sometimes an object. As a result I get an error "property1.get is not a function" because property1 is object at that time and can be accessed using property1.value.
var obj1 = attrs.property1.get('value');
}
}
所以我无法弄清楚为什么这个属性被转换为Object。当我单击向导最后一页上的“提交”按钮时,将调用这些验证。在前面的所有步骤中,property1看起来像模型,但在提交操作后,它看起来像一个对象。
有没有人遇到过这样的问题。我做错了什么但却找不到。
还观察到这种情况只是一个特定属性而不是所有属性。
答案 0 :(得分:1)
这是backbone.js
的默认行为。
项目https://github.com/powmedia/backbone-deep-model会为您解决此问题,因为它会通过执行与以下内容等效的操作来覆盖此行为:
注意:以下代码未经测试,但应该让您按预期方向
var child = new Backbone.Model({iAm: 'aChild'});
var parent = new Backbone.Model({iHave: child});
// 1. Assign the existing save method somewhere so we can use it.
var swizzledSave = parent.save;
// 2. Override the save method
parent.save = function(attrs, options, ctxt) {
attrs = attrs || this.attributes;
var toSend = {};
// 3. For each attribute in the model
_.each(attrs, function(attrVal, attrKey) {
// 4. If the attribute has the type Backbone.Model, call it's save method (which has not been overridden by the way)
if (attrVal instanceof Backbone.Model)
attrVal.save();
// 5. Otherwise, add this attribute to a list of attributes that can be sent to the server
else
toSend[attrKey] = attrVal;
}, this);
// 6. Send only those attributes.
swizzledSave(toSend, options, ctxt);
}
答案 1 :(得分:0)
我试图以这种方式解决它:虽然它很幼稚,但解决了我的目的。
if(attrs.property1.value === undefined){
value = attrs.property1.get('value'));
}else{
modules = attrs.property1.value;
}