Caching collections in backbone.js?

前端 未结 6 940
暖寄归人
暖寄归人 2021-02-03 12:50

What would be the best way to ensure that my collection stays cached and thereby only gets fetched once?

Should I implement some sort of cache layer? Should I share the

6条回答
  •  时光取名叫无心
    2021-02-03 13:07

    If by caching you actually mean a singleton, so that you can reference the same domain list from multiple places in a modular JS application, we use RequireJS for this. You can separate your collection to be a module in the application, which you then require wherever you are using it. In pseudocode:

    require(["myCollection"],
        function(myCollection) {
            var MyView = Backbone.View.extend();
            new MyView({
                collection: myCollection
            }).render();
        }
    );
    

    Your callback function will always get the same instance you returned when you define your myCollection module. Bind to that instance from all your views, and whenever it is refreshed, those views will get an event trigger and can update themselves.

提交回复
热议问题