我正在使用 Backbone 和 Marionette 开发一个小型应用程序,它在侧边栏中显示部门列表,在主容器中显示员工列表。
用户可以选择部门并按部门筛选员工列表。这是控制器和路由器的代码,但我不满意如何在控制器中初始化应用程序。
控制器:
Users = require('../collections/users.coffee')
Departments = require('../collections/departments.coffee')
UserListView = require('../views/user-list.coffee')
DepartmentListView = require('../views/department-list.coffee')
module.exports = class Controller extends Marionette.Controller
###
initialize
----------
###
initialize: ->
@users = new Users()
@userListView = new UserListView(collection: @users)
@departments = new Departments()
@departmentListView = new DepartmentListView(collection: @departments)
@app = new Backbone.Marionette.Application()
@app.addRegions(
users: '.js-users-container'
departments: '.js-departments-container'
)
@app.users.show(@userListView)
@app.departments.show(@departmentListView)
@app.on("initialize:after", ->
Backbone.history.start()
)
# App will start when the department list is rendered
@listenTo(@departmentListView, 'composite:collection:rendered', =>
@app.start()
)
# catch filter events
@listenTo(App.events, 'filter-users', (filters) =>
@users.fetch(data: filters)
)
# load the departments collection, will render department list view
@departments.fetch(data: active: 1)
###
index
-----
###
index: ->
App.events.trigger('filter-users', null)
###
getByDepartment
---------------
###
getByDepartment: (id) ->
App.events.trigger('filter-users', department: id)
路由器:
Controller = require('./controllers/main.coffee')
module.exports = class Router extends Backbone.Marionette.AppRouter
appRoutes:
"": "index"
"department/:id": "getByDepartment"
initialize: ->
@controller = new Controller()
应用程序的初始化:
router = new Router()
我该如何改进这段代码?
在此先感谢您的帮助!