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

发布于 2024-11-30 18:25:34 字数 3295 浏览 0 评论 0原文

我们目前正在启动我们的第一个 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>

We're currently kicking off our first Backbone.js project here at work. In fact it's our first major JavaScript project apart from the odd jQuery stuff.

Anyway, we struggle with the architecture for our stuff. What is the best way to sort stuff out?

We've started with having everything in separate files broken up in folders for; views, models, collections and routers and then we include everything in our index.html. The issue, though, is that this leaves us with having to check for the document ready event in every file. Is this the best way to do it?

Here's an example:

This is the file called PageModel, the first line seems wrong...

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

Then in our index.html we have:

<!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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

遇见了你 2024-12-07 18:25:34

这是我们在 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('\\

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

Rens.Models.Profile = Backbone.Model.extend({
    ...
});
+ 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 的内容

This is structure we use in our Backbone projects

<!-- 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 -->

content of 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;

and content of 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('\\

also simplified content of models/profile.js

Rens.Models.Profile = Backbone.Model.extend({
    ...
});
+ 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); } });

also simplified content of models/profile.js

别想她 2024-12-07 18:25:34

如果您正在创建这种形式的应用程序,我强烈建议您使用动态加载资源,例如 javascript 等。

您有多种选择:

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

这种系统的优点:

您需要将模型/视图/...包装在模块中,以便 require.js 可以动态加载它们。上周我在堆栈溢出中询问了这一点...您可以找到有关如何执行此操作的信息。 此处

我建议你阅读 'require.js 入门' 看看您是否喜欢使用它,

因为与所有内容一起工作 。模型/视图/...在单独的文件中在开发过程中非常方便,但在投入生产时不建议这样做。浏览器向服务器发送的请求越少越好。

If you are creating an application of this shape, i strongly suggest to use dynamic loading of your assets, like javascript and more.

you have several options for this:

i myself have no experience with LABjs, but i've been using Require.js in smaller projects for myself. But have yet to use it in a major project.

the advantages of such a system:

  • you can work with dependancies, and your models or views will only be loaded when they are requested by another part of your code. not all at the beginning.
  • require.js also provides features for minifying and agregating your code based on the dependancies you specified.
  • require.js has a few small plugins for loading in text files (if you use a templating system this could be useful, or a plugin to define the order in which files need to be loaded.
  • and require.js also has a special version for working together with jquery and its modules. (but you are not required to use this one, you can load in jquery trough manually as well)

you will need to wrap your models / views / ... in modules so require.js can load them dynamically. I asked about this here on stack overflow last week... you can find the info on how to do that here

I suggest you read the 'getting started with require.js' and see if you feel like using it.

because working with all models / views / ... in separate files is quite handy in development fase, but is defenately not recommended when going into production. the fewer requests have to be sent by the browser to the server the better.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文