我对骨骼很新,(Backbone.js 1.0.0)这是我的示例html页面,我使用视图和模型,我有一个按钮和文本字段,每次我点击该按钮,我需要将文本字段的内容显示为'< li> '标签,这是我的HTML页面
<!DOCTYPE html>
<html>
<head>
<title>Backbone Application</title>
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/underscore.js" type="text/javascript"></script>
<script src="js/backbone.js" type="text/javascript"></script>
</head>
<body>
<input type="text" id="txt1">
<button class="btn1">Save</button>
</body>
<script>
var Car = Backbone.Model.extend({
initialize: function(){
console.log('car model created...');
} ,
defaults: {
name: 'alto'
}
});
// A List of People
var CarCollection = Backbone.Collection.extend({
model: Car,
initialize: function(){
console.log('Car Collection created...');
}
});
carView = Backbone.View.extend({
tagName: 'li',
initialize: function() {
console.log('Car view created...');
},
render: function( model ) {
this.$el.html(this.model.get('name'));
return this; // returning this from render method..
console.log('rendered')
},
});
CarCollectionView = Backbone.View.extend({
tagName: 'ul',
initialize: function() {
console.log('Car Collection View created');
this.collection.on("add", this.render, this);
},
events: {
'click .btn1':'getcar'
},
getcar: function() {
console.log('Artist model changed...'+$('.nameField').val());
var car_name = $('#txt1').val();
this.collection.add({name:car_name} );
},
render: function(){
this.collection.each(function(car){
var carView1= new carView({ model: car });
this.$el.append(carView1.render().el); // calling render method manually..
}, this);
return this; // returning this for chaining..
}
});
var carCollection = new CarCollection([
{
name: 'maruthi'
}]);
var carCollectionView = new CarCollectionView({ collection: carCollection });
$(document.body).append(carCollectionView.render().el);
</script>
</html>
当我调用集合视图时它第一次工作,但是当我点击按钮时,没有任何反应,任何帮助将不胜感激
答案 0 :(得分:1)
我认为您需要首先了解events.js视图中事件的工作原理。在视图主干中指定事件哈希时,请将这些事件委派给视图el
。在您的情况下,因为按钮不是您的收藏视图的后代,所以它的事件不会被触发。
例如,如果您的HTML和集合视图稍作修改,则应触发您的事件。
HTML
<div id="carCnt">
<input type="text" id="txt1">
<button class="btn1">Save</button>
<ul id="carList"></ul>
</div>
查看
CarCollectionView = Backbone.View.extend({
el: '#carCnt',
initialize: function() {
console.log('Car Collection View created');
this.collection.on("add", this.render, this);
},
events: {
'click .btn1':'getcar'
},
getcar: function() {
console.log('Artist model changed...'+$('.nameField').val());
var car_name = $('#txt1').val();
this.collection.add({name:car_name} );
},
render: function(){
//clear list first
this.$el.find('#carList').empty();
this.collection.each(function(car){
var carView1= new carView({ model: car });
this.$el.find('#carList').append(carView1.render().el); // calling render method manually..
}, this);
return this; // returning this for chaining..
}
});
此处是指向jsbin
的链接这应该使您当前的代码正常工作,但一般情况下,您可能希望从DOM渲染集合视图并在渲染后附加它。