Search code examples
oopjavascript-frameworkjavascriptmvc

javascript oop and this


Given the following code:

JE.events = {
  self: this,
  controller: {
    init: function(){            
        $(".monthheader").click(function () { 
            JE.events.model.get($(this).attr('title')); 
            return false;
        });

        return this;
    }
  },

  model: {
    get: function(monthnum){
        ...
    }
  }

}

How would i replace the call to

JE.events.model.get(..);

by something like

self.model.get(..);

The whole code is more or less in this gist https://gist.github.com/966270 . The idea is to create a really simple MVC in js (my first attempt) that i can reuse easily. Improvements are welcome!


Solution

  • JE.events = (function {
      // Create closure
    
      // Declare controller and model as local
      var Controller = {
        init: function(){            
            $(".monthheader").click(function () { 
                Model.get($(this).attr('title')); 
                return false;
            });
    
            return this;
        }
      }
    
      var Model = {
        get: function(monthnum){
            ...
        }
      }
    
      // return object thats assigned to JE.events
      return {
        controller: Controller,
        model: Model
      }
    
    )();
    

    You may also want to look at backbone or spine which are lightweight MVC frameworks.

    They give you some simple abstractions and a lot of control. There also small and simple.

    If I were to write a micro MVC framework from scratch it would converge to either backbone or spine so it might be better to use one of those two.