我有一个包含CellModels的CellCollection的BoardView.我从数据库获取集合,然后创建CellViews.
这一切都在游泳,直到我尝试通过BoardView上的点击事件访问CellModel.我根本不能看到底层的模型…只有视图.有没有办法做到这一点?
我试图在下面包含相关代码:
CellModel = Backbone.Model.extend({}); CellCollection = Backbone.Collection.extend({ model : CellModel }); CellView = Backbone.View.extend({ className : 'cell',}); BoardView = Backbone.View.extend({ this.model.cells = new CellCollection(); render : function() { this.cellList = this.$('.cells'); return this; },allCells : function(cells) { this.cellList.html(''); this.model.cells.each(this.addCell); return this; },addCell : function(cell) { var view = new Views.CellView({ model : cell }).render(); this.cellList.append(view.el); },events : { 'click .cell' : 'analyzeCellClick',},analyzeCellClick : function(e) { // ????????? } });
我需要点击“发生”在BoardView,而不是CellView,因为它涉及到板专用的逻辑.
解决方法
我可以想到这里至少可以使用两种方法:
>在初始化时将BoardView传递给CellView,然后处理CellView中的事件:
var CellView = Backbone.View.extend({ className : 'cell',initialize: function(opts) { this.parent = opts.parent },events : { 'click' : 'analyzeCellClick',analyzeCellClick : function() { // pass the relevant CellModel to the BoardView this.parent.analyzeCellClick(this.model); } }); var BoardView = Backbone.View.extend({ // ... addCell : function(cell) { var view = new Views.CellView({ model : cell,parent : this }).render(); this.cellList.append(view.el); },analyzeCellClick : function(cell) { // do something with cell } });
这样做会有效果,但是我更喜欢没有意见调用对方的方法,因为它使它们更紧密地耦合.
>当您渲染它时,将CellModel id附加到DOM:
var CellView = Backbone.View.extend({ className : 'cell',render: function() { $(this.el).data('cellId',this.model.id) // I assume you're doing other render stuff here as well } }); var BoardView = Backbone.View.extend({ // ... analyzeCellClick : function(evt) { var cellId = $(evt.target).data('cellId'),cell = this.model.cells.get(cellId); // do something with cell } });
这可能有点清洁,因为它避免了上述紧耦合,但我认为任何一种方式都可以工作.