Self referential can.Model

I would like to create a can.Model ‘Product’ that can hold a list of Products. In pseudo coffee code:

can.Model.extend 'Product',
   resource: '/products'
,
  define:
    products:
      Value: Product.List  # "Product not defined"

This obviously doesn’t work, but I can’t figure out how to make it work. I have tried to reference ‘this.constructor’ and the like, but all has failed so far. What is the right way to do this?

You won’t be able to use Value in the definition because the creation of the definition object is immediate and Product is not yet defined. This is a common issue with circular dependencies between modules as well. To make it work, you can use the lowercase value and define a custom function that will defer the evaluation.

var Product = can.Model.extend({}, {
    define: {
        products: {
            value: function() {
                return new Product.List();
            }
        }
    }
});

Alternatively, you can modify prototype.define after creating the model to add Value.

Product.prototype.define.products.Value = Product.List;
1 Like