如果我的骨干模型有关系(例如,由骨干关系创建),那么这些关系可能是空的,导致外键字段有时是null。
如果我有几个倒扣视图模型,并且我指定了工厂,这样在遵循关系时,我就可以得到具有模型所需功能的视图模型,当它遇到一个属性null时,它会继续创建一个视图模型,将null传递为model,这很可能会破坏视图模型的大部分功能。
示例:
var ChildViewModel = kb.ViewModel.extend({
constructor: function (model, options) {
// this is the problem I'm trying to avoid - creating a view model with
// no model
if (!model) {
// just report the error somehow - the jsfiddle has the
// relevant HTML element
document.getElementById("error").innerHTML = "ChildModelView initialised without a model!";
}
kb.ViewModel.prototype.constructor.apply(this, arguments);
}
});
var ParentViewModel = kb.ViewModel.extend({
constructor: function (model, options) {
// specify factories here, because this way you can easily deal with
// reverse relationships, or complicated relationship trees when you
// have a large number of different types of view model.
kb.ViewModel.prototype.constructor.call(
this,
model,
{
factories: {relation1: ChildViewModel,
relation2: ChildViewModel},
options: options
}
);
}
});
// if we assume that relation2 is a nullable relationship, backbone-relational,
// for example, would give us a model that looks like this:
var model = new Backbone.Model({
id: 1,
relation1: new Backbone.Model({id: 2}), // this works fine
relation2: null // this causes a problem
});
var view_model = new ParentViewModel(model);还有小提琴:
发布于 2016-03-23 12:01:45
我刚刚发现了我认为可能是一个合理的解决方案。
您的工厂不必是ViewModel“类”,但可以是工厂函数。所以:
var nullable = function (view_model_class) {
var factory = function (object, options) {
if (object === null) return object;
return new view_model_class(object, options);
};
return factory;
};然后当你定义工厂的时候:
kb.ViewModel.prototype.constructor.call(
this,
model,
{
factories: {relation1: nullable(ChildViewModel),
relation2: nullable(ChildViewModel)},
options: options
}
);https://stackoverflow.com/questions/36176828
复制相似问题