Reputation: 204
console.log('Loaded inedx.js-->');
console.log(jQuery);
(function($){
console.log('In immediate block');
//Create new tweet view
var Tweet = Backbone.Model.extend({
defaults: function(){
return {
name : 'defaultName',
status : 'default status'
}
}
});
var TweetList = Backbone.Collection.extend({
model :Tweet
});
var TweetView = Backbone.View.extend({
model : new Tweet(),
tagName : 'div',
initialize : function(){
this.template = _.template($('#tweet-template').html());
},
render : function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var tweets = new TweetList();
var TweetsView = Backbone.View.extend({
model : tweets,
tagName : 'div',
el : $('#allTweetContainer'),
initialize: function(){
this.model.on('add',this.render,this);
},
render : function(){
var self = this;
_.each(this.model.toArray(),function(tweet,i){
self.$el.append((new TweetView({model:tweet})).render().$el.html());
});
return this;
}
});
$(document).ready(function (){
tweets.add(new Tweet({
status : 'status1',
author : 'author1'
}));
var tweet = new Tweet({
status : 'status1-----',
author : 'author1-------'
});
//console.log(new TweetView());
//$('#allTweetContainer').append( _.template($('#tweet-template').html(),tweet.toJSON()));
tweets.add(new Tweet({
status : 'status2',
author : 'author2'
}));
tweets.add(new Tweet({
status : 'status3',
author : 'author3'
}));
tweets.add(new Tweet({
status : 'status4',
author : 'author4'
}));
var tweetApp = new TweetsView();
tweetApp.render();
console.log(tweets.toJSON());
});
})(jQuery);
I am not able to render TweetsView.
Instead of : self.$el.append
When I used : `$('#allTweetContainer').append
it worked. But ideally it should work with self.$el.append.
I believe there must be something extra needs to be done to get proper $el which should be a jQuery variable pointing to the given el.
Any pointers would really helpful. Thanks in advance.
Upvotes: 0
Views: 3604
Reputation: 1076
You should declare el as string and not as jQuery selector. So your TweetsView should look like this:
var TweetsView = Backbone.View.extend({
model : tweets,
tagName : 'div',
el : '#allTweetContainer',
initialize: function(){
this.model.on('add',this.render,this);
},
render : function(){
var self = this;
_.each(this.model.toArray(),function(tweet,i){
self.$el.append((new TweetView({model:tweet})).render().$el.html());
});
return this;
}
});
when appending the TweetView to TweetsView, you could also do this:
_.each(this.model.toArray(),function(tweet,i){
self.$el.append((new TweetView({model:tweet})).render().el);
});
Upvotes: 3