Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I need a model in backbone.js?

I'm new to Backbone.js, and someone who comes out of the 'standard' model of JS development I'm a little unsure of how to work with the models (or when).

Views seem pretty obvious as it emulates the typical 'listen for event and do something' method that most JS dev's are familiar with.

I built a simple Todo list app and so far haven't seen a need for the model aspect so I'm curious if someone can give me some insight as to how I might apply it to this application, or if it's something that comes into play if I were working with more complex data.

Here's the JS:

Todos = (function(){

    var TodoModel = Backbone.Model.extend({

      defaults: {
          content: null
      }

    });

    var TodoView = Backbone.View.extend({

      el: $('#todos'),
      newitem: $('#new-item input'),
      noitems: $('#no-items'),

      initialize: function(){
        this.el = $(this.el);
      },

      events: {
        'submit #new-item': 'addItem',
        'click .remove-item': 'removeItem'
      },

      template: $('#item-template').html(),

      addItem: function(e) {
        e.preventDefault();
        this.noitems.remove();
        var templ = _.template(this.template);
        this.el.append(templ({content: this.newitem.val()}));
        this.newitem.val('').focus();
        return this;
      },

      removeItem: function(e){
        $(e.target).parent('.item-wrap').remove();
      }

  });

  self = {};
  self.start = function(){
    new TodoView();
  };
  return self;

});

$(function(){

    new Todos(jQuery).start();

});

Which is running here: http://sandbox.fluidbyte.org/bb-todo

like image 876
Fluidbyte Avatar asked Jul 25 '26 23:07

Fluidbyte


2 Answers

Model and Collection are needed when you have to persist the changes to the server.

Example:

var todo = new TodoModel();

creates a new model. When you have to save the save the changes, call

todo.save();

You can also pass success and error callbacks to save . Save is a wrapper around the ajax function provided by jQuery.

How to use a model in your app.

Add a url field to your model

var TodoModel = Backbone.Model.extend({

  defaults: {
      content: null
  },
  url: {
      "http://localhost";  
  }

});

Create model and save it.

addItem: function(e) {
        e.preventDefault();
        this.noitems.remove();
        var templ = _.template(this.template);
        this.el.append(templ({content: this.newitem.val()}));
        this.newitem.val('').focus();
        var todo = new TodoModel({'content':this.newitem.val()});
        todo.save();
        return this;
      },

Make sure your server is running and set the url is set correctly.

Learning Resources:

  • Check out the annotated source code of Backbone for an excellent explanation of how things fall into place behind the scenes.
  • This Quora question has links to many good resources and sample apps.
like image 189
Pramod Avatar answered Jul 27 '26 12:07

Pramod


The model is going to be useful if you ever want to save anything on the server side. Backbone's model is built around a RESTful endpoint. So if for example you set URL root to lists and then store the list information in the model, the model save and fetch methods will let you save/receive JSON describing the mode to/from the server at the lists/<id> endpoint. IE:

   ToDoListModel = Backbone.model.extend( {
         urlRoot : "lists/" } );

   // Once saved, lives at lists/5
   list = new ToDoListModel({id: 5, list: ["Take out trash", "Feed Dog"] });
   list.save();

So you can use this to interact with data that persists on the server via a RESTful interface. see this tutorial for more.

like image 45
Doug T. Avatar answered Jul 27 '26 13:07

Doug T.