Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js: Model, Collection, Router, when and why?

I'm still trying to get my head around Backbone.js I've watched some screencasts and read some tutorials. I also RTFM. But, I'm a little confused on how everyone seems to use parts of the framework to handle different tasks.

I decided to make my first shot at backbone.js in a real app, after playing with the traditional todo list app.

My app will receive a JSON object full of questions. Then, I like to have an 'ul' where I can move around those questions (next q, previous q). I already have a view that shows the buttons and notifies whenever a user clicks 'next' or 'prev'. My question is: where should I handle the logic for my 'currentQuestion', 'next', and 'previous' functionality. I've seen some folks using a Collection for this, and some other using a Model. It confuses me.

Anyone can point me some meta-code to handle this? Thanks a lot!

like image 976
fedeisas Avatar asked Feb 21 '23 15:02

fedeisas


2 Answers

There isn't really a right answer to this question. There is certainly more than one way to make it work and that is one of the nice things about Backbonejs: it is very flexible and it doesn't impose too many design choices on you.

If I were to start building what you are describing, I would certainly have:

  • a Question model
  • a Questions collection
  • a QuestionView for rendering out a single question
  • a QuestionsIndexView for displaying a list of questions

After that is where things get a little fuzzy, and it depends on what your requirements are for the app. If you wanted the state to be stored like a traditional website you might use a router and do something that looks something like this:

 ApplicationRouter = Backbone.Router.extend({

    routes: {
       "": "index",
       "question/:id": "show"
    },

    index: function() {
        // render a QuestionsIndexView...
    },

    show: function(id) {
        // find the q and render a QuestionView...
    }
 })

This is nice because state is maintained in the URLs so the user can use the browsers fwd and back buttons and things would probably work as they would expect. The problem with this is, how are we supposed to make those nextQuestion and previousQuestion buttons work?

If you make them part of the QuestionView a question would have to know what its next and previous questions' ids were. You could probably come up with a scheme to make this work, but a more elegant and frequently used pattern is to create another model that exists above all of the data models we have mentioned already called App and then make the QuestionsCollection and current_question_id attributes of this model. We would then update this current_question_id attr in the routers methods.

Now we are really cooking, our application state is not only persisted in the URLs of the browser, but it also exists at the application layer as an observable object. We can easily create a ButtonsPanelView that gets passed this App model and triggers the correct routes when its buttons are clicked. It is also trivial to implement hasNextQuestion and hasPreviousQuestion in the App model and use it to toggle or disable the respective buttons when the user cant go back or forward.

EDIT as requested:

To make an App model that exists above everything else is quite simple. You probably already have code somewhere that looks like this:

window._qs = new Questions();
window._qs.fetch();

Just do this instead:

var qs = new Questions();
window.app = new App({questions: qs});
qs.fetch();

now are Questions collection is an attribute of the app model, just as we wanted. So what is the definition for App going to look like? Again, there are many ways to go about this, but I like to use Backbone.Models's validate to make sure I don't slip into a bad state. Here's what I might do:

App = Backbone.Model.extend({

   defaults: {
      current_question_index: 0
   },

   validate: function(attrs) {

      if(typeof attrs.current_question_index !== "undefined") {
         // we are trying the change the question index,
         // so make sure it is valid
         var len = this.get("questions").length
         if(attrs.current_question_index < 0 || attrs.current_question_index >= len) {
            // returning anything prevents invalid set
            return "index is out of bounds"; 
         }
      }
    },

    hasNextQ: function() {
      var next_ind = this.get("current_question_index") + 1;
      // use the logic we already created, in validate() but
      // convert it to a bool. NOTE in javascript:
      //       !"stuff"   === false
      //       !undefined === true 
      return !this.validate({current_question_index: next_ind}); 
    },

    nextQ: function() {
      var next_ind = this.get("current_question_index") + 1;
      // validate() will prevent us from setting an invalid index
      return this.set("current_question_index", next_ind);

    }

});
like image 72
Matthew Avatar answered Mar 03 '23 15:03

Matthew


As what I understood in BackboneJS, a "model" is a unit of data. For example, a unit data for a "to-do item" would contain:

  • a date
  • a message
  • a status

These units of data are stored in a "collection". They are synonymous to "database tables" which contain "rows". But model data is not restricted to 2-d like a row. Then Backbone "views" do the logic as well a interact with the interface - more like a "View-Controller". The view houses the event handlers, the code that adds and removes elements, changes interface etc.

like image 40
Joseph Avatar answered Mar 03 '23 16:03

Joseph