键值对PARAMS在Backbone.js的路由器处理 [英] Key value pair params handling in Backbone.js Router

查看:115
本文介绍了键值对PARAMS在Backbone.js的路由器处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过键值对的PARAMS到骨干线路,并希望它被反序列化的JavaScript对象称为映射函数之前。

I want to pass key value pairs as params to Backbone routes and want it to be deserialized to a javascript object before the mapped function is called.

var MyRouter = Backbone.Router.extend({
  routes: {
    "dashboard?:params" : "show_dashboard"
  },
  show_dashboard: function(params){
     console.log(params); 
  }
}); 

当我去的http://...#dashboard键1 = VAL1&放大器;键2 = val2的?,然后{键:VAL1,KEY2:将val2},应该在控制台上进行打印

When I go to "http://...#dashboard?key1=val1&key2=val2", then {key1: "val1", key2: "val2"} should be printed on the console.

我目前使用jQuery烧烤的$ .deparam每个映射函数内的方法来获得在反序列化对象。这将是很好,如果我可以扩展路由器和定义它只有一次这样params为所有映射功能为对象的内部访问。这将是一个干净的方式做到这一点?而在这有一些陷阱?

Am currently using jQuery BBQ's $.deparam method inside each mapped function to get at the deserialized object. It would be nice if I can extend Router and define it just once so params is accessible inside all mapped functions as an object. What would be a clean way to do this? And are there some pitfalls in this??

许多感谢,

马诺

推荐答案

您应该重新定义 Backbone.Router _extractParameters 功能C>。然后,所有路由器功能将与第一个参数是被调用 PARAMS 对象。

You should redefine _extractParameters function in Backbone.Router. Then all router functions will be invoked with the first parameter being params object.

// Backbone Router with a custom parameter extractor
var Router = Backbone.Router.extend({
    routes: {
        'dashboard/:country/:city/?:params': 'whereAmIActually',
        'dashboard/?:params': 'whereAmI'
    },
    whereAmIActually: function(params, country, city){
        console.log('whereAmIActually');
        console.log(arguments);
    },
    whereAmI: function(params){
        console.log('whereAmI');
        console.log(arguments);
    },
    _extractParameters: function(route, fragment) {
        var result = route.exec(fragment).slice(1);
        result.unshift(deparam(result[result.length-1]));
        return result.slice(0,-1);
    }
});

// simplified $.deparam analog
var deparam = function(paramString){
    var result = {};
    if( ! paramString){
        return result;
    }
    $.each(paramString.split('&'), function(index, value){
        if(value){
            var param = value.split('=');
            result[param[0]] = param[1];
        }
    });
    return result;
};

var router = new Router;
Backbone.history.start();

// this call assumes that the url has been changed
Backbone.history.loadUrl('dashboard/?planet=earth&system=solar');
Backbone.history.loadUrl('dashboard/usa/la/?planet=earth&system=solar');

该工作演示是这里

这篇关于键值对PARAMS在Backbone.js的路由器处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆