Search code examples
javascriptbackbone.jsknockback.js

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


If my backbone models have relationships (for example, created by backbone-relational), those relationships might be nullable, leading the foreign key fields to sometimes be null.

If I have several knockback view models, and I've specified factories so that when following relations I get the view models with the desired functionality for the model, when it encounters an attribute that is null, it goes ahead and creates a view model passing null as the model, which likely breaks most of the view model's functionality.

Example:

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

And the fiddle:

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


Solution

  • I've just discovered what I think might be a reasonable solution.

    Your factories don't have to be ViewModel "classes", but can be factory functions. So:

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

    And then when you're defining your factories:

        kb.ViewModel.prototype.constructor.call(
            this,
            model,
            {
                factories: {relation1: nullable(ChildViewModel),
                            relation2: nullable(ChildViewModel)},
                options: options
            }
        );