rwxe2g
Last Updated: February 25, 2016
·
3.227K
· fatmuemoo
Avatar

Lazy Load A Backbone.js Model

Trying to solve the problem of lazy loading a model from a collection. The Problem: you can't depending on the get method returning the model if the collection doesn't already have the model. Conversely, using the fetch method will fetch it from the server even if the collection already has the model. So this my solution: adding a fetchOne method.

Catalog.Categories.Collection = Backbone.Collection.extend({
    fetchOne : function (id, success) {
        var result = this.get(id);
        if (typeof result !== 'undefined') {
            success.apply(result);
            return result;
        }
        var where = {};
        where[this.model.prototype.idAttribute] = id;
        var model = new this.model(where);
        this.add(model);
        model.fetch({success: function () {
            success.apply(model);
        }});
        return model;
    }
};

Calling it your code:

collection.fetchOne(123, function () {console.log(this)});

No more guessing if the model is already in the collection!. However, you have to use a call back as you can't depend on an intimidate result. You could use async false to get around this limitation.

Say Thanks
Respond