如何防止 Knockback.js 为空关系创建视图模型?

How do you prevent Knockback.js creating view models for null relations?

如果我的 backbone 模型有关系(例如,由 backbone-relational 创建),这些关系可能可以为空,导致外键字段有时为 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);

和 fiddle:

https://jsfiddle.net/vbw44vac/1/

我刚刚发现了我认为可能是合理的解决方案。

您的工厂不必是 ViewModel "classes",但可以是工厂函数。所以:

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
        }
    );