3

我很困惑如何在 Backbone.js 中实现命名空间。我一直在全球范围内创建我的模型、集合和视图。命名空间是否只是App.在模型、集合和视图类和对象的前面加上一行window.App = {};

它似乎有效,但这种方式被认为是最佳实践吗?如果没有,有什么更好的方法?

我也在App = App || {};某个地方看到过。拥有的目的是|| {}什么?

尝试命名空间 // 命名空间 window.App = {};

// Models
App.Product = Backbone.Model.extend();

// Collections
App.ProductCollection = Backbone.Collection.extend({
    model: App.Product,
    url: '/wizard'
});

// Views
App.ProductListView = Backbone.View.extend({
    el: '#photo_list',

    initialize: function() {
        this.collection.bind('reset', this.render, this);
    },

    render: function() {
        this.collection.each(function(product, index){
            $(this.el).append(new App.ProductView({ model: product }).render().el);
        }, this);
        return this;
    }
});

// Snippet

App.productList = new App.ProductCollection();
App.selectedProductList = new App.SelectedProductCollection();
App.productListView = new App.ProductListView({ collection: App.productList });
4

3 回答 3

4

您最好使用将创建或更新命名空间对象的命名空间函数,例如ns('App.Views.Homepage', Backbone.View.extend({...}).

回覆。命名空间约定 - 为了您自己的方便,您可以使用您的文件系统结构。例如,UI/Homepage/View/Main.js将成为App.UI.Homepage.View.Main(这是如果您使用模块)。

或者另一种简单的制作方法是简单且易于找到相关文件 - 根据功能创建结构,例如App.Backbone.Collection.Comments,您从更一般到更具体的位置,例如您有一个应用程序,一个主干,您有视图、模型、集合, 路由器。在每个内部,您将拥有多个特定于您的用例的模块。

例如,这是我使用的命名空间函数:

var ns = window.ns = function (nspace, payload, context) {
  payload = payload || {};

  context = context || window;

  var parts = nspace.split('.'),
    parent = context,
    currentPart = '';

  while (currentPart = parts.shift()) {
    if (parts.length !== 0) {
      parent[currentPart] = parent[currentPart] || {};
    }
    else {
      parent[currentPart] = parent[currentPart] || payload;
    }
    parent = parent[currentPart];
  }

  return parent;

用途就是我上面提到的。

于 2012-09-03T06:45:42.530 回答
1
  1. Using of namespacing in JS is considered to be best practice, keep doing this.
  2. As it's been said, using of helper function instead of 'manual' namespacing, if better. The namespace function I use, if here.
  3. App = App || {}; - does the following. If App is undefined (not initialized, used first time) || operator returns false so, second statement applied and App variable is initialized with empty object.
于 2012-09-03T08:17:59.167 回答
1

JavaScript 不支持命名空间。您的方法相当于将主干对象嵌套在全局 App 对象中。这与 JavaScript 中的命名空间差不多。请参阅 ahren 关于初始化语法的评论。

于 2012-09-03T05:54:44.807 回答