質問

私はますますバックボーンを楽しんでいます。特定のモデルに複数のビューがあることを望んでいます:

  • 各モデルが独自のLI要素を使用してビューを持っているリストビュー。
  • モデルのすべての詳細を示す詳細ビュー。

私の質問は、あるビューが別のビューと通信して以下を選出する良い方法を求めていたことです。

/** Allow a model to keep track of it's views. **/
Backbone.Model.prototype.addView = function (view) {
    // Ensure our model has a view array.
    if (typeof this.views === 'undefined')
    {
        this.views = [];
    }

    // Append our newest view to the array only if it is not already present.
    if (_.indexOf(this.views, view) === -1)
    {
        this.views.push(view);
    }
}

/** Allow a model to remove all of it's views.
 * 
 * @param {Object} args Any arguments will be provided to the view's method.
 */
Backbone.Model.prototype.unloadViews = function (args) {
    var n = (typeof this.views === 'undefined') ? 0 : this.views.length;
    for (var i = 0; i < n; i++)
    {
        var view = this.views[i];
        if (typeof view.unloadView === 'function')
        {
           view.unloadView(args);
        }
    }
}

/** Allow a model to re-render all of it's views.
 * 
 * @param {Object} args Any argyments will be provided to the view's method.
 */
Backbone.Model.prototype.renderViews = function (args) {
   var n = (typeof this.views === 'undefined') ? 0 : this.views.length;
   for (var i = 0; i < n; i++)
   {
        var view = this.views[i];
        if (typeof view.render === 'function')
        {
            view.render(args);
        }
   }
}

私の質問

  1. バックボーンを学んでいるときに何かが足りませんか?
  2. これを避けるべき理由はありますか?

追加情報

GitHubでアプリケーション(非常に初歩的な)を共有しました。 https://github.com/aarongreenlee/learning-backbone.js. 。その環境でコードを表示したい場合は、こちらからアクセスできます。 https://github.com/aarongreenlee/learning-backbone.js/commit/ea4e61d934d2f987726720e81c479f9d9bb86e09#diff-2 (最初のコミット)。

お時間をいただきありがとうございます!

役に立ちましたか?

解決

さて、あなたの意見にはリファレンスのようなツリーがありますが、モデルはあなたの意見について知らないはずです!

モデルからの変更を聞くためにビューを設定し、それに応じてイベントを反応させる必要があります(それは再レンダリングします)。

これにより、ソフトウェアの下部(モデル、モデルの堅実なもの)とより高い部分、ビューの間の相互参照を避けます。古典的なMVC分離。

したがって、addViewsを移動し、backbone.viewにビューを削除すると、それが良いはずです。 Sproutcoreが提供するものと同じように、階層ビューシステムを作成します。

楽しむ!

他のヒント

ドキュメントクラウドのジェレミーアシュケナスのTwitterからの答えが来ました

@aarongreenleeそれを避ける理由はありません - あなたがあなたの意見を互いに互いに参照したいなら、それは確かに合法です。 - @jashkenas

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top