backbone.js - accessing a model from a click event

后端 未结 3 1472
鱼传尺愫
鱼传尺愫 2021-02-01 10:11

I have a BoardView containing a CellCollection of CellModels. I fetch the collection from the db and then create the CellViews.

This all works swimmingly until I try to

3条回答
  •  半阙折子戏
    2021-02-01 10:35

    I would let the CellView handle the click event, but it will just trigger a Backbone event:

    var CellView = Backbone.View.extend({
        className : 'cell',
    
        initialize: function() {
            _.bindAll(this, 'analyzeCellClick');
        }
    
        events : {
            'click' : 'analyzeCellClick',
        },
    
        analyzeCellClick : function() {
            this.trigger('cellClicked', this.model);
        }
    });
    
    var BoardView = Backbone.View.extend({
        // ...
    
        addCell : function(cell) {
            var view = new Views.CellView({
                model : cell
            }).render();
    
            this.cellList.append(view.el);
            view.bind('cellClicked', function(cell) {
                  this.analyzeCellClick(cell);
                };
        },
    
        analyzeCellClick : function(cell) {
            // do something with cell
        }
    });
    

提交回复
热议问题