javascript - 如何防止 Knockback.js 创建空关系的 View 模型?

标签 javascript backbone.js knockback.js

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

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

最佳答案

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

您的工厂不必是 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/

相关文章:

javascript - jquery 加载窗口未执行

javascript - 使用 requirejs 和 backbonejs 创建/访问全局对象

javascript - Knockback.js 生产准备好了吗?

javascript - Knockback.js:当主干保存更新模型时,如何更新 View ?

typescript - Typescript 可以导入 Webpack UMD 吗?

javascript - 用 `ng-repeat` 给一个元素不同的颜色

javascript - 如何从指令内部观察变量的变化?

javascript - 嵌套 Backbone 模型未获取数据

javascript - 使用 Moment.js 实现 24 小时倒数计时器

backbone.js - Backbonejs 集合长度始终为零