gpt4 book ai didi

jquery - 如何将 Backbone 事件处理函数作为字符串传递?

转载 作者:行者123 更新时间:2023-12-01 07:51:02 25 4
gpt4 key购买 nike

我有一个主干 View (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" });

问题是,事件没有触发,那么这段代码有什么问题吗?

最佳答案

您可以直接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.

例如,

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');
}
});

和演示 http://jsfiddle.net/rzm21q0g/

关于jquery - 如何将 Backbone 事件处理函数作为字符串传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30073037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com