首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何防止Knockback.js为空关系创建视图模型?

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

Stack Overflow用户
提问于 2016-03-23 11:23:05
回答 1查看 42关注 0票数 0

如果我的骨干模型有关系(例如,由骨干关系创建),那么这些关系可能是空的,导致外键字段有时是null

如果我有几个倒扣视图模型,并且我指定了工厂,这样在遵循关系时,我就可以得到具有模型所需功能的视图模型,当它遇到一个属性null时,它会继续创建一个视图模型,将null传递为model,这很可能会破坏视图模型的大部分功能。

示例:

代码语言:javascript
复制
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);

还有小提琴:

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-23 12:01:45

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

您的工厂不必是ViewModel“类”,但可以是工厂函数。所以:

代码语言:javascript
复制
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;
};

然后当你定义工厂的时候:

代码语言:javascript
复制
    kb.ViewModel.prototype.constructor.call(
        this,
        model,
        {
            factories: {relation1: nullable(ChildViewModel),
                        relation2: nullable(ChildViewModel)},
            options: options
        }
    );
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36176828

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档