backbone.js - accessing a model from a click event

后端 未结 3 1431
鱼传尺愫
鱼传尺愫 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:52

    I can think of at least two approaches you might use here:

    1. Pass the BoardView to the CellView at initialization, and then handle the event in the 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
          }
      });
      

      This would work, but I prefer to not have views call each other's methods, as it makes them more tightly coupled.

    2. Attach the CellModel id to the DOM when you render it:

      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
          }
      });
      

      This is probably a little cleaner, in that it avoids the tight coupling mentioned above, but I think either way would work.

提交回复
热议问题