如果我的主干模型具有关系(例如,由主干关系创建),这些关系可能可为空,导致外键字段有时为 null
。
如果我有几个击退 View 模型,并且我已经指定了工厂,以便在遵循关系时,当遇到 null
属性时,我会得到具有模型所需功能的 View 模型,它会继续创建一个 View 模型,传递 null
作为 model
,这可能会破坏 View 模型的大部分功能。
示例:
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);
还有 fiddle :
最佳答案
我刚刚发现了我认为可能合理的解决方案。
您的工厂不必是 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
}
);
关于javascript - 如何防止 Knockback.js 创建空关系的 View 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36176828/