`

JavascriptMVC 之 route 的 history功能的使用

阅读更多

JavascriptMVC 之 route 的 history功能的使用

如果使用过ExtJs的同学,应该会知道它的history的功能,而在jquery MVC 框架中的route也具体有这种功能,

不过history的功能只是route中的其中一个功能。

在这里,只是举例介绍如何使用route的history的功能。


首先,定义一个router.js对象,
steal( 'jquery/controller', 'jquery/controller/route'
)
.then(function($) {
    $.Controller('Project.Router',
    /** @Static */
    {
        defaults : {
            nav1 : ''
        }
    },
    /** @Prototype */
    {
  /**
  *  这里是重点,它是实现history的核心
  * 监听route的变化,也就是type的变化,每当type变化时,会触发这个事件 
  */
        '{$.route} change' : function(el, ev, attr, how, newVal, oldVal) {
            switch (attr) {
                case 'type':
                    this.options.nav1 = newVal;
                    this.nav1_change(newVal);
                    break;
            }
        },
        nav1_change : function(val) {
            switch (val) {
                case 'home':
                    console.info("打开主页");
                    break;
                case 'task':
                    console.info("打开我的任务");
                break;
            }
        }
    })
});

接着,我们在模块初始化时,创建一个$.route对象,还有就是把router对象实例绑定到body元素上,再设置一下,默认打开页面,
那么,我们每次进去系统时,就会打开这个页面。当然,我们也可以把每次最后一个页面保存到cookie中,那么,我们F5刷新时,
页面会自动跳会到最后一次访问的页面。
steal(
 './project.css',    // application CSS file
 './models/models.js',  // steals all your models
 './fixtures/fixtures.js',// sets up fixtures for your models
 'lib/wijmo',
 'jquery/lang/json',
 'jquery/controller',
 'jquery/model',
 'jquery/view/ejs',
 'project/controllers',
 function(){     // configure your application
  
  //创建$.route对象
  $.route( "url/:type" );
  //创建router对象实例
     $('body').project_router();
//     $.route.attrs({type : 'home'});
  //默认打开页面
  location.hash = "#!url/home";
  
  $("#dContent").project_proc();
  
  
 });
最后,就是点击菜单时,如何变化type,
steal( 'jquery/controller','jquery/controller/view','jquery/view/ejs','jquery/model'
)
.then(function($) {
 //控制器
    $.Controller('project.proc',
    /** @Static */
    {
        defaults : {
        }
    },
    /** @Prototype */
    {
       'div.action a click':function(el,ev){
         var id = el.attr("href").substring(1);
   //在这里,我们点击菜单时,会改变type的值,这样会触发route的change事件
         $.route.attrs({type : id});
   return false;
       },
       init:function(){
       }
    }
)});

从上面我们可以看到通过3步就可以实现这个history功能,是不是很方便。

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics