2

Backbone アプリケーション内で CommonJS モジュールを使用して頭を悩ませようとしているので、スケルトンの Backbone View が で定義されてい/views/categories/edit.jsます。

app.Views.quoteCategoriesEdit = app.Ui.ModalView.extend({

    className: '',

    template: JST["templates/quotes/categories/quote-categories-edit.html"],
    events: {
        'click [data-key="save"]': 'save',
        'click [data-key="cancel"]': 'cancel'
    },
    initialize: function (options) {
        var that = this;
        _.bindAll(this, 'save', 'cancel');
        app.Collections.quotesCategories.on('change add', function () {
            that.remove();
        });
    },

    render: function () {
        var that = this;
        // boilerplate render code
        return this;
    }

});

これを CommonJS モジュールに変換して Browserify で使用する方法を誰かが教えてくれたら、とてもありがたいですし、アプリケーションの残りの部分をモジュール化する方法を理解するのに本当に役立ちます! ありがとう

4

1 に答える 1

7
//once you get things into folders/files, this path may change
//but for now I'm assuming all your views will live in the same directory 
var ModalView = require('./modal-view');

var QuoteCategoriesEdit = ModalView.extend({

    className: '',

    template: JST["templates/quotes/categories/quote-categories-edit.html"],
    events: {
        'click [data-key="save"]': 'save',
        'click [data-key="cancel"]': 'cancel'
    },
    initialize: function (options) {
        var that = this;
        _.bindAll(this, 'save', 'cancel');
        app.Collections.quotesCategories.on('change add', function () {
            that.remove();
        });
    },

    render: function () {
        var that = this;
        // boilerplate render code
        return this;
    }

});
//Simplest convention is just 1-class-per-module
//Just export the constructor function
module.exports = QuoteCategoriesEdit;

コメントからのフォローアップの質問:

これはとてもありがたいです!app.Collections.quotesCategories にどのようにアプローチしますか? アプリの名前空間にすべてを格納しますか? コレクション自体が必要ですか?

したがって、「アプリ」名前空間の考え方は、モジュラー/commonjs/browserify/requirejs の反対です。appオブジェクトはもう必要ありません。このコレクションの新しいインスタンスを作成する必要があるモジュールは、それで十分ですvar QuotesCategories = require('app/collections/quotes-categories');。グローバルまたは名前空間オブジェクトはもうありません。ほとんどのビューは、コンストラクター関数で必要なモデル/コレクションを取得しますoptionsfetchモデルのほとんどはコレクションを呼び出すことによって作成され、コレクションのほとんどはルーターによってインスタンス化されます。

options.collectionああ、そうです、この特定の例では、ビュー以外のコードでコレクションを作成し、それをコンストラクターパラメーターを介してビューに渡すのがおそらく最善です。ただし、ビューでコレクションをインスタンス化することを本当に望んでいると判断したapp場合、それはグローバル名前空間オブジェクトからではなくrequire、コメントで説明したように呼び出しから来るだけです。

于 2013-07-15T17:50:00.450 に答える