gpt4 book ai didi

backbone.js - 没有绑定(bind)的backbone.js中的自定义事件

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

我正在寻找一种更好的方法来使用 Backbone 实现 PubSub 类型的功能。我目前正在实现它,但正在寻找一种更好的方法来实现它。

示例路由代码

var AppRouter = Backbone.Router.extend({
customEvents: _.extend({}, Backbone.Events),

routes: {
"login": "login"
},

//Injecting custom event
login: function(){
this.before(function () {
app.showView('#Content', new LoginView({customEvents:this.customEvents}), "login", true);

});
},

//Injecting custom event
otherView: function(){
this.before(function () {
app.showView('#Header', new OtherView({customEvents:this.customEvents}), "login", true);

});
},

..... more code

});

示例查看代码。请注意,我正在使用 bind 来监听 customEvent。这工作正常,但正在寻找替代方法
LoginView = Backbone.View.extend({
initialize: function(options){
this.customEvents = options.customEvents;
this.customEvents.bind('app:loggedin', this.loggedIn);

},

loggedIn: function(){
console.log("LOG CHANGED");
},

...more code

我更愿意将我的事件与我在 View 中使用的其他事件一起保留。不知道如何实现这一点。我应该扩展 View 类吗?

我想对我的观点做些什么
  LoginView = Backbone.View.extend({
events: {
"app:loggin" : "loggedIn"
},

loggedIn: function(){
console.log("LOG CHANGED");
},

...more code

最佳答案

要点:https://gist.github.com/vermilion1/5600032

演示:http://jsfiddle.net/vpetrychuk/3NVG9/1

代码预览:

// -- BASE VIEW ------------------

var BaseView = Backbone.View.extend({
constructor : function (options) {
Backbone.View.prototype.constructor.apply(this, arguments);
this._eventAggregator = options && options.eventAggregator || this;
this._parseTriggers();
},
_parseTriggers : function () {
_.each(this.triggers || {}, function (fn, event) {
var handler = this[fn];
if (_.isFunction(handler)) {
this.listenTo(this._eventAggregator, event, handler);
}
},
this);
}
});

// -- TEST ------------------

var View = BaseView.extend({
triggers : {
'hello' : 'helloHandler',
'bye' : 'byeHandler'
},
helloHandler : function (name) {
console.log('hello, ' + name);
},
byeHandler : function (name) {
console.log('bye, ' + name);
}
});

var view1 = new View();
view1.trigger('hello', 'dude 1'); // -> hello, dude 1
view1.trigger('bye', 'dude 1'); // -> bye, dude 1

var vent = _.extend({}, Backbone.Events);
var view2 = new View({eventAggregator:vent});
vent.trigger('hello', 'dude 2'); // -> hello, dude 2
vent.trigger('bye', 'dude 2'); // -> bye, dude 2

关于backbone.js - 没有绑定(bind)的backbone.js中的自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16600949/

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