I have a Backbone view (SearchView) which have several search handlers. The search handler function must be dynamically passed as a string based on some process type.
Here is my code
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" });
The problem is, event is not firing, So what is wrong in this code??
You can directly define your events hash as a function:
The events property may also be defined as a function that returns an events hash, to make it easier to programmatically define your events, as well as inherit them from parent views.
For example,
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');
}
});
and a demo http://jsfiddle.net/rzm21q0g/