2012-12-19 40 views
0

我在导轨3骨干视图,其中初始化具有动态地与这样将内容添加到使用Rails

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

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

回答

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'); 

会工作。 我没有改变引用的代码,以便您可以轻松地在那里搜索。 Refrence:http://japhr.blogspot.in/2011/08/getting-started-with-backbonejs-view.html

0

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

解决方案可以指定body作为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是集可能是错的,但你可以试试这个。