title: Adding more functions to Backbone Models
body: <p>I am attempting to add some functions to backbone so that I can communicate with mongodb. Now I know this won't work client side; however, I do like backbone's functionality for server side model logic as well. I noticed that I would be doing a bunch of repeat work if I kept adding the same functionality for each model so decided to create a "app_model" file to extend backbone when I'm server side. I also don't want to override the standard Backbone functions because they will be useful client side. </p>
  
  <p>So let's take this user class for instance:</p>
  
  <pre><code>var Backbone = require('./app_model');
  
  var User = Backbone.Model.extend({
      name : "users",
      defaults: function() {
          return {
              username: "default",
              role: 2,
              created: new Date(),
              updated: new Date(),
              logged: new Date()
          };
      },
      idAttribute: "username",
      /**
       * A predefined listing of user roles
       */
      userRoles: [
          "admin",  //0
          "author", //1
          "user"    //2
      ],
      initialize: function() {
          if(!!app) {
             this.svrInit();
          }
      }
  });
  
  module.exports = User;
  </code></pre>
  
  <p>And I want to append functions onto backbone by using my "app_model.js" file, which looks something like this currently:</p>
  
  <pre><code>var Backbone = require('backbone'),
    Deferred = require('Deferred'),
    when = Deferred.when;
  
  Backbone.Model.prototype.svrInit = function() {
      //TODO: perhaps the code below should be made static some how so we don't have a bunch of instances of collection
      var model = this;
      if(!!app.db){
          app.db.collection(this.name,function(err,collection){
              model.collection = collection;
          });
      }
  };
  
  Backbone.Model.prototype.svrSave = function() {
      var model = this.toJSON();
      var dfd = new Deferred();
      this.collection.insert(model, {safe:true}, function(err, result){
          dfd.resolve();
      });
      return dfd;
  };
  
  Backbone.Model.prototype.svrFind = function(options) {
      var model = this.toJSON();
      var dfd = new Deferred();
      this.collection.find(options, {safe:true}, function(err, result){
          dfd.resolve();
      });
      return dfd;
  };
  
  module.exports = Backbone;
  </code></pre>
  
  <p>I ran my tests when I abstracted this out and it seemed to work alright. Is there a better way to do any of this? Any pit falls? I am using the global "app" variable, is that bad? If so what are some ways around it? I do find it ugly that I had to put <code>this.svrInit()</code> inside the init function at the model level is there anyway to automatically make that happen after creation?</p>