Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion about Models in Backbone + React application

Here's an example that uses Backbone with React.

He defines a Model: var _todos = new Backbone.Model();

And then adds two functions to it:

var TodoStore = _.extend(_todos, {
  areAllComplete: function() {
    return _.every(_todos.keys(), function(id){
      return _todos.get(id).complete;
    });
  },
  getAll: function() {
    return _todos.toJSON();
  }
});

What I don't understand is why areAllComplete is being applied to a Model instead of to a Collection.

Shouldn't this be a function in a Collection that will get all of its models and check that complete attribute.

Similarly, I would expect getAll to belong to a Collection - get all of its models.

This example seems to replace Collection with Model.

Maybe I don't totally understand how models are used.

like image 205
pushkin Avatar asked Jul 10 '15 15:07

pushkin


1 Answers

That example is using Backbone.Model in a fairly wierd way in my opinion.

This is where it's adding new todos to the store:

var id = Date.now();
  _todos.set(id, {
    id: id,
    complete: false,
    text: text
  });
}

What it's basically doing is setting every todo-item as an attribute of the Model, using the id as the attribute name. It ends up with _todos.attributes looking something like below

{
  "1436600629317": {
    "id": 1436600629317,
    "complete": false,
    "text": "foo"
  },
  "1436600629706": {
    "id": 1436600629706,
    "complete": false,
    "text": "bar"
  }
}

That's the same output you get from _todos.toJSON(). I've no idea why they decided to implement it like that, if they were to try using Backbone.Sync they'd end up with a server API that's not exactly RESTful. It seems strange to use Backbone without leveraging any of the things Backbone provides. There's a reference to the change event here but I don't see it being used anywhere. You could easily reimplement that store using any regular JS object.

The only thing that example seem to be actually using from Backbone is Backbone.Events in the dispatcher. You're totally right that using a Collection would make way more sense because then you could actually make it talk to a REST based server API. That example seems to only use Backbone for the sake of using Backbone.

like image 177
ivarni Avatar answered Sep 30 '22 10:09

ivarni