我有一个路由器类,它实际上具有单独的视图和集合哈希值,如下所述。当我在视图渲染方法中获取实例时,如何设置集合的 url 参数。
路由器类
Router = (function() {
'use strict';
var
viewHash = {},
collectionsHash = {},
EvtCalRouter, startRouter;
// Set up the Backbone Router.
// Evaluates URL with parameters and maps them to functions contained within the Router.
// This enables us to do things like allow users to bookmark search results.
// See "http://backbonejs.org/#Router" for more info.
EvtCalRouter = Backbone.Router.extend({
// Define the Routes we care about.
// See "http://backbonejs.org/#Router-routes" for more info.
routes: {
"": "home",
"route1": "route1"
}
buildSearchScreen: function() {
collectionsHash['events'] = ESPN.apps.ADTG.EC.EventsCollection.newInstance({});
},
startRouter = function() {
new EvtCalRouter();
Backbone.history.start();
};
// Start routing functionality
$(document).ready(startRouter);
// For any module that needs to know...
$(document).ready(function() {
$(document).trigger(ESPN.apps.ADTG.EC.events.ecInit);
});
// Public API
return {
getCollection: function(name) {
return collectionsHash[name] || {};
}
};
})();
Collection类是这样定义的
Collection = (function() {
var Events = Backbone.Collection.extend({
initialize: function(props) {
this.url = props.url;
alert(this.url);
}
});
return {
newInstance: function(options) {
return new Events(options);
}
};
})();
获取集合时如何设置集合的url参数 视图渲染方法中的实例。
您应该能够在选项哈希中传递 url:
Collection.newInstance({url: "your url"});
但是。
要初始化集合,您需要传递模型数组,因此您需要更改集合定义:
Collection = (function(){
var Events;
Events = Backbone.Collection.extend({
initialize: function(models, options){
this.url = options.url;
alert(this.url);
}
});
return {
newInstance : function(models, options) { return new Events(models, options); }
};
})();
我不确定为什么你想要为你的收藏提供动态网址。 :/ 您可能想定义该集合适用于哪个模型...但是,您也可以通过选项传递它。
Collection.newInstance([
//array of models...
], {
url: "meh"
});
编辑:
如果您需要动态 url,但大部分内容仍然相同,您可以将 url 定义为函数:
Events = Backbone.Collection.extend({
url: function(urlOptions) {
return 'yourDomain/resources?'+ urlOptions; // just return the url as a string
}
});
jsfiddle 示例:
jsfiddle.net/sbjaz/13