var ListView = Backbone.View.extend({
el: $('hello'),
events: {
'click .myName': 'namefunc',
},
initialize: function() {
var stuff = new FieldCollection();
stuff.parse();
var self = this;
stuff.fetch({
success: function (collection, response) {
console.log(response);
self.render(response);
return response;
}
});
},
render:function(output){
_.each(output, function(i){
p=i.name;
$(this.el).append("<button class='myName'>"+p+"</button><h1>"+i.img+"</h1><br/>");
},this);
},
namefunc:function(){
alert('hiii');
}
});
如何使用函数namefunc绑定带有myName类的按钮.........我试过如上面的代码所示... plz help
答案 0 :(得分:1)
执行'click .myName': 'namefunc',
或'click #myName': 'namefunc',
答案 1 :(得分:1)
我重构了你的代码。我还提出了一些意见,以帮助您实现目标并更多地了解主干。
initialize: function() {
var self = this;
_.bindAll(this, 'render');
this.collection = new FieldCollection();
this.collection.parse();
this.collection.fetch({
success: function (collection, response) {
console.log(response);
self.render();
}
});
},
render:function(){
var self = this;
_.each(this.collection, function(model) {
// here you should create subviews and delegate events within particular view
// i.e:
// self.buttonViews.push(new ButtonView({ model: model}));
// but for now you can use data-id attribute to match the button you clicked
$(self.el).append("<button class='myName' data-id=" + model.id + ">" + model.name + "</button><h1>" + model.img + "</h1><br/>");
});
},
namefunc:function(){
//use data-id attribute we put in button tag earlier to catch the id
//and use this.collection.get('id') function to get the model you want to get parameters of
}