1

初めてのバックボーン アプリケーションを開発しようとしています。すべて問題ないようですが、ビューをレンダリングして html を追加すると$el、ページに何もレンダリングされません。残りのサービス呼び出しは正常に完了しました。DOM が確実に作成されるようにBackbone.Router.extend内部で宣言されています。$(document).ready(function () {});私のjavascriptをデバッグすると、要素はinnerHTMLelプロパティに正しい値を含むようになりますが、ページ全体がレンダリングされると、この値はページに表示されません。

私は何を間違っていますか?

私のビューコード:

window.ProductsListView = Backbone.View.extend({

  id: 'tblProducts',
  tagName: 'div',

  initialize: function (options) {
    this.model.on('reset', this.render, this);
  },

  render: function () {
    // save a reference to the view object
    var self = this;

    // instantiate and render children
    this.model.each(function (item) {
      var itemView = new ProductListItemView({ model: item });
      var elValue = itemView.render().el;
      self.$el.append(elValue);  // Here: the $el innerHTML is ok, but in the page it disappear. The id of element is div#tblProducts, so the element seems correct
    });

    return this;
  }
});

window.ProductListItemView = Backbone.View.extend({

  tagName: 'div',

  template: _.template(
      '<%= title %>'
    ),

  initialize: function (options) {

    this.model.on('change', this.render, this);
    this.model.on('reset', this.render, this);
    this.model.on('destroy', this.close, this);
  },

  render: function () {
    $(this.el).html(this.template(this.model.toJSON()));
    // $(this.el).html('aaaaaa');  // This neither works: it's not a template problem

    return this;
  },

  close: function () {
    $(this.el).unbind();
    $(this.el).remove();
  }
});

ここで製品をロードします ( 内Backbone.Router.extend)。これは正しく実行されます:

this.productsList = new ProductsCollection();
this.productsListView = new ProductsListView({ model: this.productsList });
this.productsList.fetch();

そして、これは私がレンダリングしたいhtml要素です:

<div id="tblProducts">
</div>

前もって感謝します、

4

2 に答える 2

2

投稿したコードから、実際に DOM に挿入したりProductsListView、既存の DOM 要素にアタッチしたりしていません。

私が気に入っているのは、2 種類のビューがあることです。

  • サーバーから返されたデータに基づいて動的に生成されるもの
  • ページに既に存在するもの

通常、リストの場合、リストはすでにページに存在し、そのアイテムは動的に追加されます。私はあなたのコードを取り、この jsfiddleで少し再構築しました。ProductListViewが既存の にバインドulProductItemViewれ、 がコレクションに追加されると動的に追加されることがわかります。

Collection.reset を示すように jsfiddle を更新

于 2013-03-06T08:46:38.167 に答える
1

elレンダリングされているかどうかにかかわらず、プロパティはビュー内に存在します。要素が渡されない場合 (空の div)、Backbone は要素を作成するため、そこでは問題ないとは言えません。

ビューをレンダリングしたい場合は、要素のコンテナーを決定する必要があります。ビューをアタッチしたい html はありますか?

ellikeでビューを呼び出して、コンテナ要素を渡してみてください

this.productsListView = new ProductsListView({ model: this.productsList, el : $("#container") });

もちろん、ビューを作成して後で DOM にアタッチすることもできます。

el: $("#someElementID") //grab an existing element
el.append(view.render().el);

ビューは、どこかにアタッチするまで dom に存在しません。

于 2013-03-06T08:36:11.160 に答える