2

アイテムのリストとプレースホルダーの「新しい」アイテムが表示されるBackbone.jsを使用してアプリケーションを構築しています。コンテナは、すべてのサブビューを保持してレンダリングするビューです。

しばらく検索しましたが、機能させることができません。問題は、テンプレートの [追加] ボタンがイベントを発生させないことです。後でレンダリングが行われるため、イベントが割り当てられていないと思います。他の投稿を読むと、これは Backbone.js で処理する必要がありますが、そうではないようです。後でjQueryイベントハンドラーを追加するrender()と仕事ができますが、それは解決策にはならないと思います。

ビューの関連コードは次のとおりです。

template: _.template($("#template-time-new").html()),
events: {
  'click #btn-new-time': 'onButtonNewClick'
},
render: function() {
  this.$el.html(this.template());

  return this;
},

onButtonNewClick: function() {
  return false; // in this case: prevent page reload
}

私のテンプレート(翡翠):

script(type="text/template", id="template-time-new").
<h3>
  <label for="new-time-name" class="muted">Name:</label>
  <input id="new-time-name" type="text">
</h3>
<div class="time-inner">
  <form class="form-horizontal">
    <label for="new-time-start" class="muted">From:</label>
    <input id="new-time-start" type="datetime-local">

    <label for="new-time-end" class="muted">to</label> 
    <input id="new-time-end" type="datetime-local">

    <button class="btn" id="btn-new-time">
      Add
    </button>
  </form>
</div>

編集:

親ビューのコードは次のとおりです。

initialize: function() {
  this.newView = new TimeSpanNewView; // <---- the view that is not really working

  this.render();

  // bind event handlers
  this.collection.on('all', this.render, this);
  // fetch data
  this.collection.fetch();
},

render: function() {
  var self = this;

  self.$el.empty();

  if ( self.collection.length > 0 ) {
    self.collection.each(function(timespan) {
      var subView = new TimeSpanView({ // sub views for the items, everything fine here
        model: timespan
      });

      subView.render()
      self.$el.append(subView.el);
    });
  } else {
    self.$el.text("Nothing found.");
  }

  self.$el.append(self.newView.render().el);

  return self;
}
4

1 に答える 1

2

前のコメントを削除しました。render()親ビューで毎回レンダリングする必要があります。しかし、代わりにself.$el.html("");tryを実行しself.$el.children().detach()ます。そして、子ビューを次のように追加します

self.$el.append(self.newView.render().el);

説明: $el には既に子ビューが含まれており、子ビューを完全に削除したくありません。したがって、これで detach() を呼び出す必要があります。子ビューの DOM オブジェクトをページから削除しますが、完全には削除しません。

于 2013-07-11T21:46:28.747 に答える