0

我在 Rails 3 中有一个主干视图,其中初始化有一行动态创建一个带有这样的类的 div

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

div 的内容在一个生态文件“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

主干代码中,el首先被设置this._ensureElement();然后initialize被调用。所以我相信这里el不会按照你想要的方式设置。这将只是一个普通的div.

解决方案可以指定bodyelfor 视图(可能不是最佳实践),将模板的内容包装在<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 回答
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 回答