這是解決方案的一個工作示例 - jsfiddle.net/avrelian/dGr8Y/,只是jsFiddle不允許Backbone.history.navigate
方法正常工作。
假設,我們有一個按鈕
<input class="fetch-button" type="button" value="Fetch" />
和處理
$('.fetch-button').click(function() {
Backbone.history.navigate('posts/?author=martin', true);
});
這是我們的帖子收集
var Posts = Backbone.Collection.extend({
url: 'api/posts'
});
這是我們使用自定義參數提取
路由器
var Router = Backbone.Router.extend({
routes: {
'posts/?:filters': 'filterPosts'
},
filterPosts: function(filters){
posts.fetch({data: $.param(filters)});
},
_extractParameters: function(route, fragment) {
var result = route.exec(fragment).slice(1);
result.unshift(deparam(result[result.length-1]));
return result.slice(0,-1);
}
});
它是簡化$ .deparam模擬。你可以使用你自己的。
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 posts = new Posts;
var router = new Router;
Backbone.history.start();
當用戶點擊該按鈕地址欄更改爲myapp.com/s/#posts?author=martin
的實例。請注意標記#
。我們使用一個哈希查詢字符串。當然,你可以使用push state
,但它還沒有被廣泛使用。
請參閱我對類似問題的回答[stackoverflow.com/questions/7445353/key-value-pair-params-handling-in-backbone-js-router/8184621#8184621](http://stackoverflow。 com/questions/7445353/key-value-pair-params-handling-in-backbone-js-router/8184621)#8184621) – avrelian 2012-08-12 07:28:49
謝謝你,看起來有趣,我會看看它,你怎麼看待這個回答:http:// stackoverflow。com/questions/6659283/backbone-js-fetch-with-parameters – jlstr 2012-08-12 14:34:59
我認爲從路由器開始是一個更好的主意。您可以(以編程方式或從地址欄導航)到'someapp.com/search/Tokyo?price_min = 80&price_max = 300',路由器解析您的參數,並通過'collect.fetch({data:$ .param({price_min:80,price_max:300})});'或通過您的集合的自定義「sync」方法。當然,你可以用相反的方式來做,但在這種情況下,處理書籤鏈接將會很困難。 – avrelian 2012-08-12 17:59:54