Search code examples
javascriptbackbone.jsreactjs-flux

Flux - who should change data in models which are in collection?


I have Backbone collection of models and list view for this collection.

<ul>
  <li><input type="checkbox"/> <span>Title</span></li>
  ...
</ul>

When user click on checkbox I execute this code

Actions.save({id: model.cid, data: {select: true}})

This action trigger event save-model in dispatcher and here the question - Who should handle this event?

I have two options:

1) collection

Dispatcher.on('save-model', function (event) {
  var model = collection.get(event.cid);
  if (model) {
    model.set(event.data);
  }
});

2) each model in collection should listen dispathcer

Dispatcher.on('save-model', function (event) {
  if (model.cid === event.cid) {
    model.set(event.data);
  }
});

Solution

  • I will go for option #1 - collection. My point of view is this way the event only need to be processed once. If bind it in the model, say your collection has 1k models, 1k events will be triggered to check if it match, and then set the attribute.