.为什么要搞JavaScript MVC了 ? 有些人可能不理解, 我刚开始也不理解,但是有一些现实里的需求,让我主动去寻找一个这样的MVC框架, 我的需求很简单,因为我想有一个好的js代码组织结构, 我想让自己的思路变的更加清晰。 我终于找到了--Jamal , 一个轻量级的基于jQuery的JavaScript MVC框架。

Jamal的作者Timo在Jamal刚开始的版本发布的时候,做了一个图,搞了一个什么dispatcher, 可笑的是,国内的某些人竟然把这个图转来转去的当成是宝, 呵呵,我问了Timo本人,他是这么说的:
Hey Alex,

    this is a slide from a presentation at the very beginning of jamal.
    This is not wrong in general, but there is no dispatcher anymore. The
    configuration, what controller is called, is now handled within the
    body class.

    A short explanation of this structure is:
    - Interactions of the user are reflected in . events. So
    bind events to the dom within the controller.
    - Data is handled in the models so all XHR should go there
    - The view modifies the dom

    This is all convention, Jamal doesn't force you to do it like this...

Greetings,
 Timo


Timo这段话已经说的很清楚了,网上流传的那张图早就作废了。 现在的Jamal 0.4.1支持jQuery1.3。
就像Timo说的, 代码是通过config方法和load方法来寻找controller和action。MVC简单来说是这么约定的:

    
 1. C(ontroller) - 因为和用户交互的都是.事件,所以应该在controller里和dom绑定事件。
 2. M(odel) - 在models里面是进行data处理,所以会放一些ajax逻辑,以及对本地数据库的操作(Jamal没有实现,但是因为项目需求我会集成到里面)。
 3. V(iew) - 而在view里当然是对用户dom的修改。


当你下载了Jamal 0.4.1,里面会带例子的。今天研究了Jamal的源码,有一些心得:

    
代码1505行:
    $(function(){
    $j = jamal = jamal();
    $j.start();
    });


这段代码在页面加载以后启动Jamal。 start方法里面会调用关键的load方法去根据页面body的class属性去识别哪个controller,哪个action,所以你的页面body标签的class属性必须这么写:

    
class="jamal {controller:'Foos',action:'index',debug:true}"

一个页面对应一个controller,一个controller对应一个action。 如果想像rails一样,想写多个action,那么可以这样去模拟:

    $j.c({Clients: {
          index: function () {
                  this.new();
                  // or
                 $('.new').click(function(){
                 $j.current.new();
         });
    },

          new: function() {}
    }});



$j.c代表controller。 这样,可以更细致的组织你的controller代码了。
如果想在Jamal里扩展自己的方法,可以这样:


    jamal.fn.extend(jamal.fn.m.prototype,  {
        createTable: function(option){
            return true;
           // 你可以在你的model里通过重载此方法实现你具体的方法。
        },
    });

最后看看我的代码组织目录:
JavaScript MVC之Jamal_第1张图片