我是骨干新手。我只想知道全局事件触发并绑定每个事件的回调。我试过这样......
landing.view.js
'use strict';
var $ = require('jquery');
var Backbone = require('backbone');
var _ = require('underscore');
var tpl = require('text!components/landing-page/templates/landing-page.html');
return Backbone.View.extend({
el: '.view-container',
template: _.template($(tpl).html()),
events:{
'click .btn-show': 'showUsersListHandler'
},
initialize: function(){
this.render();
},
render: function(){
$(this.el).html(this.template);
return this;
},
showUsersListHandler: function(evt){
Backbone.trigger('userPage', {trigger:true});
}
});
another.view.js
'use strict';
var Backbone = require('backbone');
var _ = require('underscore');
var $ = require('jquery');
var tpl = require('text!components/user-logs-listing/templates/user-logs-listing-tpl.html');
return Backbone.View.extend({
el: '.users-list-container',
template: _.template($(tpl).html()),
initialize: function(){
this.render();
},
render: function(){
$(this.el).html(this.template);
}
});
应用路由器
'use strict';
var $ = require('jquery');
var Backbone = require('backbone');
var viewContainer = require('inits/utils');
var landingView = require('components/landing-page/views/landing-page');
var userListingView = require('components/user-logs-listing/views/user-logs-listing.view');
return Backbone.Router.extend({
routes: {
"": "landing",
"usersList": "usersPage"
//'*path': 'defaultRoute'
},
initailize: function(){
Backbone.listenTo(Backbone, 'userPage', this.usersPage)
},
landing: function(){
viewContainer.createContainer('view-container');
new landingView();
},
usersPage: function(){
//$('.view-container').remove();
viewContainer.createContainer('users-list-container');
new userListingView();
}
});
如果我单击着陆视图中的按钮,它应该触发'userPage',它应该导航到#UsersPage。问题是如何触发和绑定全局事件的回调????帮助我获得正确的解决方案!感谢。
答案 0 :(得分:0)
好的,我建议这样做:
制作一个新文件Events.js
<强> Events.js 强>
define(['underscore',
'backbone'
], function(_, Backbone) {
"use strict";
return _.extend({}, Backbone.Events);
});
现在,在 landing.view.js
中 var $ = require('jquery');
var Backbone = require('backbone');
var _ = require('underscore');
var Events = require('Events');
var tpl = require('text!components/landing-page/templates/landing-page.html');
-----
Events.on('customEvent1',this.customCallback1);
-----
同样,在 another.view.js
中var Backbone = require('backbone');
var _ = require('underscore');
var Events = require('Events');
var $ = require('jquery');
var tpl = require('text!components/user-logs-listing/templates/user-logs-listing-tpl.html');
-----
Events.on('customEvent2',this.customCallback2);
-----
现在,您想要触发这些自定义事件的任何地方,请执行以下操作:
Events.trigger('customEvent1');
Events.trigger('customEvent2');
并包含您想要使用它的事件文件。
希望它有所帮助!!