0

Rails 3 にバックボーン ビューがあり、初期化には、このようなクラスで div を動的に作成する行があります。

initialize: () ->
  $('body').append('<div class="new"></div>')

div の内容は、eco ファイル「new.jst.eco」にあります。現在のコード:

class TestApp.Views.NewDivView extends Backbone.View
  el: '.new' # newly created in the initialize method.
  template: JST['new']

render: ->
  $(@el).html(@template())
  this

initiaize: () ->
  $('body').append('<div class="new"></div>')

同じビューで新しく作成された div にテンプレートのコンテンツを追加するにはどうすればよいですか?

4

2 に答える 2

0

私はそれを仮定します:

var event_html = template($('#calendar-event-template').html());  // Add apt. selector for template.
$(event_html({title: title, description: description})).appendTo($(el))

どこ :

$(el) = $('body .new');

動作します。そこで簡単に検索できるように、参照からコードを変更していません。 参照: http://japhr.blogspot.in/2011/08/getting-started-with-backbonejs-view.html

于 2012-12-19T05:06:21.953 に答える
0

バックボーン コードから、elが最初に設定され、this._ensureElement();次にinitialize呼び出されます。ですから、ここelはあなたが望むようには設定されないと思います。そして、それは単なるプレーンになりdivます。

body解決策として、 for ビューとして指定しel(ベスト プラクティスではない可能性があります)、テンプレートのコンテンツを でラップします<div class="new"></div>

<div class="new">
  <!-- put template content here -->
</div>

そして、あなたが次のように書くことができるビュー(私はcoffeescriptの構文を知らないので、javascriptで書いています):

view = Backbone.View.extend({
  el : 'body',

  template : "respective_template",

  render : function() {
    this.$el.append(this.template());
    this.setElement(".new"); /* this will change the el for the view from body to a div with class new and will delegate all bound events also if any */

    return this;
  }     
});

設定されているというコードからの仮定はel間違っているかもしれませんが、これを試してみてください。

于 2012-12-19T06:31:38.637 に答える