javascript - 在 requirejs 中返回 Backbone 集合的标准方法

标签 javascript backbone.js requirejs

我在不同的文章中看到了关于如何从 RequireJS 定义返回主干集合(或 View ,就此而言)的不同示例。例如:

define(['models/person'], function( person ) {
    var personCollection = Backbone.Collection.extend({
        model: person,
        url: "api/person"

    });
    // do this?
    return new personCollection();
    // or this?
    //return personCollection;
});

这两种方法都有内存优势吗?是否有标准的设计模式来规定应该使用哪个?

同样的问题也适用于 View ,因为我也看到它们以两种方式完成。

最佳答案

我会采用第二种方式,因为那样您会收到对“蓝图”的引用,而不是对象本身。在大多数情况下,人们应该希望自己初始化对象创建。

此外,即使您只想创建集合的单个实例,我也建议您使用这样的工厂方法:

define(['models/person'], function( person ) {
    var personCollection = Backbone.Collection.extend({...}),
        singleCollection,
        export = {
          getInstance = function (options) {
            if (!singleCollection) {
              singleCollection = new personCollection(options);
            }
            return singleCollection;
          }
        }

    return export;
});

然后你可以这样调用它:

require('models/person', function (person) {
  var personCollection = person.getInstance(options);
}

关于javascript - 在 requirejs 中返回 Backbone 集合的标准方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15637601/

相关文章:

javascript - 用于在集合上添加事件的主干绑定(bind)

javascript - 主干内存泄漏与否?

javascript - 在 requirejs + marionette 应用程序中传递应用程序对象

javascript - Framework7 inside webview页面未加载

javascript - Angular 依赖注入(inject)性能

javascript - 从助手获取模板数据

javascript - 如何使用 grunt 创建 require.js 包

javascript - 使用 "deep"数组 react useState 不重新渲染组件

javascript - 主干模型节省了客户端和服务器之间的更改循环

javascript - 使用 requireJS 进行敲除映射