我有一个用于执行搜索的集合。我的大部分收藏都扩展了这个搜索收藏。
它有一个对象,其中包含用于搜索的参数。集合的用户可以调用setSearchParam
,我有一个方法buildSearchString
可以构建要调用的 URL 的搜索部分(我在 REST url 中使用 Matrix 参数)。
window.SearchCollection = Backbone.Collection.extend({
initialize : function() {
this.params = {}; // holds parameters for searching
},
// Set a search param
setSearchParam: function(param, value) {
if (typeof value === 'undefined') return;
if (typeof this.params === 'undefined') this.params = {};
this.params[param] = value;
},
setSearchParams : function(paramMap) {
_.extend(this.params, paramMap);
},
// Build Matrix params for search. This could just as easily be a standard URL string
buildSearchString: function() {
var search = [];
var i = 0;
for (var key in this.params) {
var value = this.params[key];
if (utils.isEmpty(value)) continue;
search[i++] = ";";
search[i++] = key;
search[i++] = "=";
search[i++] = value;
}
return search.join('');
}
});
然后当我创建一个集合时,我扩展它:
window.BookingCollection = window.SearchCollection.extend({
model: Booking,
url: function(){
var urlString = BASE_REST_URL + "bookings/";
// Build the matrix params for the REST URL
urlString += this.buildSearchString();
return urlString;
}
});
然后,这个集合的用户可以像这样使用它:
var bookings = new BookingCollection();
bookings.setSearchParam("name", "hello");