我寫了一個簡單的程序來創建表單發佈。當創建新帖子時,標題將被添加到文檔中,並且當點擊標題時,點擊活動並顯示警報。當我創建另一篇文章的標題也顯示了第一篇文章的標題,但是,沒有人點擊時彈出警告。backbone.js當點擊添加新的DOM元素時點擊事件不會觸發
var PostModel = Backbone.Model.extend({
defaults: {
"title": "",
"postTxt":""
}
});
<!-- Collection -->
var PostCollection = Backbone.Collection.extend({
url: '/UserPosts',
model: PostModel
});
<!-- Views -->
var PostModelView = Backbone.View.extend({
model: new PostModel(),
tagName: 'li',
template: _.template($('#post-title').html()),
initialize: function() {
console.log('Initialized PostModelView........');
},
events: {
'click a' : 'showAlert'
},
showAlert: function(){
console.log('event');
alert("You clicked : " + this.model.get('title'));
},
render: function() {
console.log('Running render() of PostModelView.....');
var htmloutput = this.template(this.model.toJSON());
this.$el.html(htmloutput);
return this;
}
});
var postmodelview = new PostModelView();
var postcollection = new PostCollection();
var PostCollectionView = Backbone.View.extend({
collection: postcollection,
tagName: 'ul',
initialize: function() {
console.log('Initialized PostCollectionView .......');
this.collection.on('add', this.render, this);
this.collection.on('remove', this.render, this);
console.log('postcollectionview $el: ' + this.$el.html());
},
render: function() {
this.collection.each(function(postmodel) {
console.log(JSON.stringify(postmodel));
var postmodelview = new PostModelView({model: postmodel});
console.log(JSON.stringify(postmodelview));
//var htmlout = postmodelview.render().$el;
var htmlout = this.$el.append(postmodelview.render().$el);
$('#postcontainer').html('');
$('#postcontainer').append(htmlout);
//this.$el.append(htmlout);
},this);
return this;
}
});
function createPost() {
var postcollectionview = new PostCollectionView();
console.log('running creatPost()');
var postmodel = new PostModel({ title: $('#title').val(), postTxt: $('#postTxt').val() });
postcollection.create(postmodel);
console.log("postcollection: " + JSON.stringify(postcollection.toJSON()));
$('#title').val(''); //clears the input field
$('#postTxt').val(''); // clears the input field
}
爲什麼不在PostCollectionView中使用「collection」屬性而不是「model」?現在看起來很奇怪。 – MiguelSR
此外,此行「var postmodelview = new PostModelView();」。 什麼是應該做最後兩行「createPost」功能?我不明白你的代碼。 無論如何,我認爲問題出在「$('#postcontainer')。append(htmlout);」。也許#postcontainer不在View的$ el中。 – MiguelSR
@MiguelSR在PostCollectionView中更改爲「collection」屬性而不是「model」。 createPost()中的最後兩行清除輸入字段。 – parthi82