我有一个Backbone视图(SearchView),它有几个搜索处理程序。必须根据某种进程类型将搜索处理函数动态传递为字符串。
这是我的代码
SearchView = Backbone.View.extend({
el: wrapper,
process : "defaultHandler",
event: {},
template: _.template("<div id='cpntainer'><input type='button' id='search' value='Click Here'/><div>"),
initialize: function(options){
this.render();
this.vent = options.vent;
this.options = options.process
this.event = this.getEvent();
},
getEvent : function(){
return {"click #search": this.process};
},
searchHandler1: function( event ){
alert('calling Handler1');
},
searchHandler2: function( event ){
alert('calling Handler1');
},
searchHandler3: function( event ){
alert('calling Handler1');
},
defaultHandler: function( event ){
alert('calling Deafault Handler');
},
render: function () {
this.$el.html(this.template());
return this;
}
});
var mainEvent = _.extend({}, Backbone.Events);
var myView = new SearchView({ vent: mainEvent, process: "searchHandler1" });
问题是,事件没有触发,那么这段代码有什么问题?
答案 0 :(得分:2)
您可以直接define your events hash as a function:
events属性也可以定义为返回的函数 事件哈希,以便更容易以编程方式定义您的事件, 以及从父视图继承它们。
例如,
SearchView = Backbone.View.extend({
process : "defaultHandler",
events: function () {
return {"click #search": this.process};
},
initialize: function (options) {
this.process = options.process;
},
searchHandler1: function (event) {
console.log('calling Handler1');
},
searchHandler2: function (event) {
console.log('calling Handler2');
}
});
答案 1 :(得分:1)
您的事件对象名为event
- 它应为events
。看看是否有帮助。
关于您的第二个问题(下面的评论),您设置的this.options = options.process
应为this.process = options.process
。
答案 2 :(得分:0)
在processName上使用带有switch block的单个事件处理程序有什么问题?试试这个:
SearchView = Backbone.View.extend({
el: wrapper,
process : "defaultHandler",
events: {
'click #search': 'onSearchClick'
},
template: _.template("<div id='cpntainer'><input type='button' id='search' value='Click Here'/><div>"),
initialize: function(options){
this.render();
this.vent = options.vent;
this.process = options.process
},
onSearchClick: function(event){
switch(this.process){
case 'searchHandler1':
alert('calling Handler1');
break;
case 'searchHandler2':
alert('calling Handler2');
break;
case 'searchHandler3':
alert('calling Handler3');
break;
default:
alert('calling Deafault Handler');
break;
}
},
render: function () {
this.$el.html(this.template());
return this;
}
});
var mainEvent = _.extend({}, Backbone.Events);
var myView = new SearchView({ vent: mainEvent, process: "searchHandler1" });