Richie

Sometimes at night when I look up at the stars, and see the whole sky just laid out there, don't you think I ain't remembering it all. I still got dreams like anybody else, and ever so often, I am thinking about how things might of been. And then, all of a sudden, I'm forty, fifty, sixty years old, you know?

CorMVC - 一个基于jQuery的js MVC实验性项目

项目地址: CorMVC - jQuery-powered Model-View-Controller Framework
demo站点: http://www.bennadel.com/resources/projects/cormvc/demo,进入后点CONTACTS进入演示界面

实现上很简单,也很有意思

主要机制

   
以demo站点上的联系人功能为例,下面这个联系人列表可以执行edit、delete等操作
   
Edit按钮的html如下: <a href="#/contacts/edit/${id}" class="edit">Edit</a>
所以点击Edit时页面不会提交、刷新,但url地址会变化,变成类似这样:
http://www.bennadel.com/resources/projects/cormvc/demo/#/contacts/edit/18
框架关键对象为corMVC.js中的Application,html文档加载完后,Application对象通过setInterval监控window.location的变化,类似上面这种url变化,Application根据#/contacts/edit/18的内容,在已注册的controller中查找匹配项,由controller加载数据(model),通过view完成显示

demo项目结构概览
   
实现联系人增删改查所需的html都在index.htm中,执行某操作时,将相关html显示出来,不相关的部分隐藏
controller、model等都使用javascript定义
比如controller中主要代码如下,主要是向Application中注册伪url与controller处理方法的对应关系
// I am the controller class.
function Controller(){
    
// Route URL events to the controller's event handlers.
    this.route( "/contacts/"this.index );
    
this.route( "/contacts/add/"this.addContact );
    
this.route( "/contacts/edit/:id"this.editContact );
    
this.route( "/contacts/delete/:id"this.deleteContact );   
    
// Set default properties.
    this.currentView = null;
    
this.contactListView = null;
    
this.contactFormView = null;
};

// Extend the core application controller (REQUIRED).
Controller.prototype = new application.Controller();

// I initialize the controller. I get called once the application starts
//
 running (or when the controller is registered - if the application is 
//
 already running). At that point, the DOM is available and all the other 
//
 model and view classes will have been added to the system.
Controller.prototype.init = function(){
    
this.contactListView = application.getView( "ContactList" );
    
this.contactFormView = application.getView( "ContactForm" );
};
model类似于一个poco实体
view中的contact_form.js、contact_list.js等,实现显示相关的一些html操作
model里面的contact_service.js,将demo所用的数据保存在js对象中,并提供CRUD操作方法;而contact_service_mock.js则演示通过ajax操作数据

评价
M不是领域模型,只是用javascript简单的定义的实体对象,类似poco实体
伪语义的url只是为了方便路由到特定的 controller,跟搜索没有关系,这样的方案用于前端需要搜索的地方是不合适的,用于交互性或者后端业务处理的地方还是有一定的可行性
这样做的话对服务器端简化不少,服务器端不需要处理view的东西,可以采用web service、mvc框架或者简单的http接口等类似的RPC接口就可以,不受限制
项目只能说是实验性质的,主要处理机制上有点独特的地方
整体来看:目前这个方式对开发效率、代码组织结构方面并没有体现出明显的效果,定义controller、view的操作方面等比较繁琐

参考: corMVC: An jQuery-based MVC Framework 12.22.09

posted on 2009-12-23 21:31  riccc  阅读(3645)  评论(8编辑  收藏  举报

导航