backbone.js - accessing a model from a click event

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

    Good question! I think the best solution would be to implement an

    EventBus aka EventDispatcher

    to coordinate all events among the different areas of your application.

    Going that route seems clean, loosely coupled, easy to implement, extendable and it is actually suggested by the backbone documentation, see Backbone Docs

    Please also read more on the topic here and here because (even though I tried hard) my own explanation seems kind of mediocre to me.

    Five step explanation:

    1. Create an EventBus in your main or somewhere else as a util and include/require it

       var dispatcher = _.clone(Backbone.Events); // or _.extends 
      
    2. Add one or more callback hanlder(s) to it

       dispatcher.CELL_CLICK = 'cellClicked'
      
    3. Add a trigger to the Eventlistener of your childView (here: the CellView)

       dispatcher.trigger(dispatcher.CELL_CLICK , this.model);
      
    4. Add a Listener to the Initialize function of your parentView (here: the BoardView)

       eventBus.on(eventBus.CARD_CLICK, this.cardClick);
      
    5. Define the corresponding Callback within of your parentView (and add it to your _.bindAll)

       cellClicked: function(model) {
       // do what you want with your data here
       console.log(model.get('someFnOrAttribute')
       }
      

提交回复
热议问题