构建Backbone.js项目的好方法是什么?

时间:2011-08-19 07:53:41

标签: javascript architecture backbone.js

我们目前正在开展我们的第一个Backbone.js项目。事实上,除了奇怪的jQuery之外,它是我们的第一个主要的JavaScript项目。

无论如何,我们为我们的东西挣扎着架构。排序的最佳方法是什么?

我们已经开始将所有内容分散在文件夹中的单独文件中;视图,模型,集合和路由器,然后我们在index.html中包含所有内容。但问题是,这使我们不得不在每个文件中检查文档就绪事件。这是最好的方法吗?

以下是一个例子:

这是名为PageModel的文件,第一行似乎错了......

$(function(){
     app.models.Page = Backbone.Model.extend({
    //stuff
    });
});

然后在index.html我们有:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>

        <link href="assets/css/style.css" rel="stylesheet" type="text/css" />

        <script type="text/javascript">
            var app            = app                 || {};

            app.models         = app.models         || {};
            app.collections    = app.collections     || {};
            app.views        = app.views         || {};
            app.routers        = app.collections     || {};
            app.templates     = app.templates        || {};

            app.models.griditems = app.models.griditems || {};
            app.views.griditems = app.views.griditems || {};
        </script>

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
        <script src="assets/js/libs/json2.js" type="text/javascript"></script>
        <script src="assets/js/libs/underscore-1.1.7.min.js" type="text/javascript"></script>
        <script src="assets/js/libs/backbone-0.5.3.min.js" type="text/javascript"></script>

        <script src="assets/js/models/GridItemModel.js" type="text/javascript"></script>
        <script src="assets/js/models/GalleryGridItemModel.js" type="text/javascript"></script>
        <script src="assets/js/models/NewsGridItemModel.js" type="text/javascript"></script>
        <script src="assets/js/models/VideoGridItemModel.js" type="text/javascript"></script>

        <script src="assets/js/collections/GridCollection.js" type="text/javascript"></script>

        <script src="assets/js/templates/Submenu.js" type="text/javascript"></script>
        <script src="assets/js/templates/GalleryGridItemTemplate.js" type="text/javascript"></script>

        <script src="assets/js/views/GridView.js" type="text/javascript"></script>
        <script src="assets/js/views/GridItemView.js" type="text/javascript"></script>
        <script src="assets/js/views/GalleryGridItemView.js" type="text/javascript"></script>
        <script src="assets/js/views/VideoGridItemView.js" type="text/javascript"></script>

        <script src="assets/js/routers/Router.js" type="text/javascript"></script>

        <script src="assets/js/Application.js" type="text/javascript"></script>
    </head>

    <body>
    </body>
</html>

2 个答案:

答案 0 :(得分:4)

这是我们在Backbone项目中使用的结构

<!-- Libs Section -->
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/libs/jquery-1.5.2.min.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/libs/jquery.validate.min.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/libs/jquery.maskedinput-1.3.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/libs/jquery.mousewheel.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/libs/jquery.scrollpane.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/libs/fileuploader.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/libs/modernizr.min.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/libs/json2.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/libs/underscore-min.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/libs/backbone-min.js")"></script>
<!-- Libs Section -->

<!-- Core Section -->
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/config.js")"></script> <!-- Global configs -->
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/core.js")"></script> <!-- Core methods for easier working with views, models and collections + additional useful utils -->
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/app.js")"></script> <!-- Application object inherites core.js as prototype -->
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/renisans.js")"></script> <!-- Project Object. Creates Namespace and Extends it with project specific methods -->
<!-- Core Section -->

<!-- Routers Section -->
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/routers/workspace.js")"></script>
<!-- Routers Section -->

<!-- Models Section -->
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/models/profile.js")"></script>
    ...
<!-- Models Section -->

<!-- Collections Section -->
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/collections/messages.js")"></script>
    ...
<!-- Collections Section -->

<!-- Views Section -->
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/views/workspace.js")"></script>
    ...
<!-- Views Section -->

<!-- Localization Section -->
    <script type="text/javascript" src="@Url.Content("~/Content/static/js/localizations/ru_RU.js")"></script>
<!-- Localization Section -->

<!-- Init Section -->
    <script type="text/javascript">
        $(function() {
            Rens.container = $('.l-wrapper'); // Some parameters
            Rens.init({
                Localization: LocalizationStrings || {}, // Object with localization strings
                Profile: {
                    // Bootstraping initial data to Profile model
                }
            });
        });
    </script>
<!-- Init Section -->

app.js的内容

var App = function() {
        this.Views = {};
        this.Routers = {};
        this.Models = {};
        this.Collections = {};
        this.User = {};

        this.router = null;
        this.view = null;
        this.baseLocation = null;

        this.beforeInit = function() {};
        this.afterInit = function() {};

        this.init = function(initData) {
            if (typeof(this.beforeInit) === 'function') {
                this.beforeInit.apply(this, arguments);
            }

            if (this.Views.Workspace) {
                this.view = new this.Views.Workspace();
            }
            this.baseLocation = window.location.href.replace(/[?#].*/, '') == Config.web.host;

            if (this.Routers.Workspace) {
                this.router = new this.Routers.Workspace(initData);
            }
            this.view && this.view.setListeners && this.view.setListeners();
            Backbone.history.start();

            if (typeof(this.afterInit) === 'function') {
                this.afterInit.apply(this, arguments);
            }
        }.bind(this);
    };

App.prototype = Core;

和renisans.js的内容

var Rens = new App();

$.extend(Rens, {
    container: null,

    Error: function(data) {
        // Handling error
    },

    Localization: function(dictionary) {
        return {
            get: function(name) {
                var argumentsList = Array.prototype.slice.call(arguments),
                    strings = argumentsList.slice(1),
                    text = this[name];

                if (text && strings.length) {
                    $(strings).each(function(i, string) {
                        var reg = new RegExp('\\$' + i, 'go');

                        text = text.replace(reg, string);
                    });
                }
                return text || 'SLB.Localization.' + name + ' not found!';
            }.bind(dictionary)
        }
    },

    formatDate: function(rawDate) {
        var timestamp = /\d+/.exec(rawDate)[0],
            date = Rens.DateUTC(timestamp),
            months = Rens.Localization.get('months');

        return {
            date: date,
            fullDate: [date.dd, months[date.mm], date.hh].join(' '),
            shortDate: [date.dd, date.MM, date.hh].join('.')
        };
    },

    beforeInit: function(initData) {
        this.Localization = new this.Localization(initData.Localization);
    }
});

还简化了models / profile.js的内容

Rens.Models.Profile = Backbone.Model.extend({
    ...
});

答案 1 :(得分:4)

如果您要创建此形状的应用程序,我强烈建议您使用动态加载资源,例如javascript等。

你有几个选择:

我自己没有LABjs的经验,但我一直在小型项目中使用Require.js。但还没有在一个重大项目中使用它。

这种系统的优点:

  • 您可以使用依赖项,只有在代码的其他部分请求时才会加载模型或视图。不是所有的开始。
  • require.js还提供了根据您指定的依赖项缩小和聚合代码的功能。
  • require.js有一些小插件可以加载文本文件(如果你使用模板系统这可能很有用,或者是一个插件来定义文件需要加载的顺序。
  • 和require.js还有working together with jquery及其模块的特殊版本。 (但你不需要使用这个,你也可以手动加载jquery槽)

您需要将模型/ views / ...包装在模块中,以便require.js可以动态加载它们。上周我在堆栈溢出问题上询问了这个问题...你可以找到关于如何做到这一点的信息here

我建议您阅读“getting started with require.js”,看看您是否愿意使用它。

因为在单独的文件中使用所有模型/视图/ ...在开发中非常方便,但在投入生产时是不可取的。浏览器向服务器发送的请求越少越好。