canjscanjs-model

Can.Model: creating model instances from plain objects


I have a can.Model with defined findOne, findAll methods. Sometimes however it is required to create model instances from plain objects, e.g. these objects are bootstrapped in html as globals during initial page load.

The problem is that these instances are not merged with instances stored in can.Model.store object. Moreover they are not getting stored there while they have defined id attribute. Is it expected behaviour? What is the right pattern to create model instances bootstrapped in html as variables?


Solution

  • Only models that are bound to (e.g. having data displayed on the page) will be added to the store. The store is only used for keeping those models. If nobody is listening to model changes there is no need to keep them stored (in fact, it would create a memory leak). You can verify it like this:

    var model = new MyModel({ name: 'David' });
    
    model.bind('change', function() {});