Man*_*n K 8 javascript params query-parameters backbone.js
我想将键值对作为参数传递给Backbone路由,并希望在调用映射函数之前将其反序列化为javascript对象.
var MyRouter = Backbone.Router.extend({
routes: {
"dashboard?:params" : "show_dashboard"
},
show_dashboard: function(params){
console.log(params);
}
});
Run Code Online (Sandbox Code Playgroud)
当我转到"http://...#dashboard?key1 = val1&key2 = val2"时,应在控制台上打印{key1:"val1",key2:"val2"}.
我目前在每个映射函数中使用jQuery BBQ的$ .deparam方法来获取反序列化的对象.如果我可以扩展路由器并将其定义一次就可以了,因此可以在所有映射函数中作为对象访问params.什么是干净的方式来做到这一点?这有什么陷阱?
非常感谢,
马诺
avr*_*ian 10
你应该重新定义_extractParameters函数Backbone.Router.然后将使用第一个参数作为params对象调用所有路由器函数.
// 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');
Run Code Online (Sandbox Code Playgroud)
工作演示就在这里.
| 归档时间: |
|
| 查看次数: |
10598 次 |
| 最近记录: |