Module/Template/Model example

by Chase Wilson

HTML

<script src="https://raw.github.com/gist/1331147/c8e3607d7ed195cc0c2841de6b65eea05184ce07/Events.Latched.js"></script>
<script src="https://raw.github.com/gist/1331431/4f91b6385973746a70c0c17ebdffb93aec460b3c/Module.Model.js"></script>
<script src="https://raw.github.com/gist/1331165/47d487a7822326d67c9133eceb550a808dca059c/Class.Template.js"></script>
<script type="text/template" id="person-wrapper">
    <p>Hello there <%=$this.get('name')%>.</p>
    <%=$this.getChild('bio')%>
</script>
<script type="text/template" id="person-bio">
    <p><%=$this.get('text')%></p>
</script>

CSS

div {height: 200px; background: #efefef;}

JavaScript

window.addEvent('domready',function(){
    var mod = new Module({
         data: {
            name: 'Chase'
        }
        ,template: $('person-wrapper').get('text')
    });
      
    var bio = new Module({
         data:{
             text: 'Chase lives in Southern California.'
        }
        ,template: $('person-bio').get('text')
    });
    
    
    mod.setChild('bio',bio);
    $(mod).inject(document.body);

});


(function(win){

  var Module = win.Module = new Class({
     Implements:[Options,Events,Template]
    ,children: {}
    ,options:{
         template: null
    }
      
    ,get:function(key){
      var method = this['get'+key.capitalize()];
      if(method) return method();
      
      if(this.model && this.model.get(key)){
        return this.model.get(key);
      }
      
    }
    ,initialize: function(options){
      var self = this.$this = this;

      this.setOptions(options);
      this.id = String.uniqueID();
      
        if(options.data){
          this.setModel(this.options.data);
      }
        
      this.attachEvents();
      this.container = new Element('div.module-container');
      //this.$this = this.model;
      this.setTemplate(self.options.template);
      this.loadTemplate();
    }
    ,attachEvents: function(){
      var self = this;
      this.addEvent('template.loaded',function(){
        var model = self.getModel();
        self.container.set('html',self.compile(self));
        self.appendChildren();
      });
    }
    ,setModel:function(model){
        this.model = (model instanceof Model)? model : new Model({data:model});
      console.log(this.model);
      return this.model;
    }
    ,getModel: function(){
      return this.model || this.setModel();
    }
    ,loadTemplate: function(tmpl){
      var self = this;
      setTimeout(function(){
        self.fireEvent('template.loaded');
      }, 1000);
    }
    ,setChild:function(key,module){
      this.children[key] = module;
    }
    ,getChild:...