【问题标题】:Adding content to an element created dynamically in Backbone with Rails使用 Rails 向 Backbone 中动态创建的元素添加内容
【发布时间】:2012-12-06 09:57:56
【问题描述】:

我在 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中?

【问题讨论】:

    标签: javascript ruby-on-rails-3 backbone.js coffeescript


    【解决方案1】:

    我想:

    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

    【讨论】:

      【解决方案2】:

      backbone code 开始,首先在this._ensureElement(); 中设置el,然后调用initialize。所以我相信el 不会按照你想要的方式设置。它只是一个普通的div

      一种解决方案可以是,将body 指定为el 以供查看(可能不是最佳做法),将模板的内容包装在&lt;div class="new"&gt;&lt;/div&gt; 中。

      <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-08-30
        • 1970-01-01
        • 2015-01-24
        • 2013-09-29
        • 2017-08-15
        • 2021-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多