Take a look at this snippet below:
<script>
$(function(){
var to_username = "alex";
window.Persona = Backbone.Model.extend({
});
window.PersonaList = Backbone.Collection.extend({
model:Persona,
url:function(){
return '/js/personas/approval/user?to_username=' + to_username;
}
});
window.Personas = new PersonaList;
window.CheckView = Backbone.View.extend({
tagName:'div',
template: _.template($("#checkbox_friends").html()),
initialize: function(){
this.model.bind('change', this.render, this);
},
render:function(){
$(this.el).html(this.template({}));
return this;
}
});
window.AppView = Backbone.View.extend({
el:$("#add_friend_holder"),
coreTemplate: _.template($("#add_friend_templ").html()),
initialize:function(){
this.render();
Personas.bind('reset', this.addAllBoxes, this);
Personas.bind('all',this.render, this);
Personas.fetch({
success:function(){
},
error:function(){
}
});
},
addOneBox:function(persona){
var check_view = new CheckView({'model':persona});
this.$("#friend_ticker").append(check_view.render().el); //DOESNT APPEND!!!
},
addAllBoxes:function(){
Personas.each(this.addOneBox);
},
render:function(){
this.el.html(this.coreTemplate({}));
}
});
window.App = new AppView;
});
</script>
<div id="add_friend_holder"></div>
<style>
#friend_ticker{
padding:6px;
border:1px solid #ccc;
background:#fff;
width:200px;
}
</style>
<script type="text/template" id="add_friend_templ">
<button class="btn danger">Add Friend</button>
<div id="friend_ticker">
</div>
</script>
<script type="text/template" id="checkbox_friends">
<input type="checkbox">
Print this
</script>
Everything works except for one line:
this.$("#friend_ticker").append(check_view.render().el);
If I console.log(check_view.render().el) ….it’s all good.
Except, my script doesn’t find this.$(“#friend_ticker”), even though it’s right there. I dont’ see anything printed on the screen.
Could it be that you are rendering the view 2 times after fetch as you bind to two Collection events.
The first call fills the view with subtemplates. The second then renders the parent empty again.