示例化集合 Backbone.js

li9yvcax  于 2024-01-09  发布在  其他
关注(0)|答案(1)|浏览(172)

我有一个路由器类,它实际上为视图和集合提供了单独的哈希值,如下所述。当我在视图呈现方法中获取示例时,如何设置集合的url参数。
路由器类

  1. Router = (function() {
  2. 'use strict';
  3. var
  4. viewHash = {},
  5. collectionsHash = {},
  6. EvtCalRouter, startRouter;
  7. // Set up the Backbone Router.
  8. // Evaluates URL with parameters and maps them to functions contained within the Router.
  9. // This enables us to do things like allow users to bookmark search results.
  10. // See "http://backbonejs.org/#Router" for more info.
  11. EvtCalRouter = Backbone.Router.extend({
  12. // Define the Routes we care about.
  13. // See "http://backbonejs.org/#Router-routes" for more info.
  14. routes: {
  15. "": "home",
  16. "route1": "route1"
  17. }
  18. buildSearchScreen: function() {
  19. collectionsHash['events'] = ESPN.apps.ADTG.EC.EventsCollection.newInstance({});
  20. },
  21. startRouter = function() {
  22. new EvtCalRouter();
  23. Backbone.history.start();
  24. };
  25. // Start routing functionality
  26. $(document).ready(startRouter);
  27. // For any module that needs to know...
  28. $(document).ready(function() {
  29. $(document).trigger(ESPN.apps.ADTG.EC.events.ecInit);
  30. });
  31. // Public API
  32. return {
  33. getCollection: function(name) {
  34. return collectionsHash[name] || {};
  35. }
  36. };
  37. })();

字符串
集合类是这样定义的

  1. Collection = (function() {
  2. var Events = Backbone.Collection.extend({
  3. initialize: function(props) {
  4. this.url = props.url;
  5. alert(this.url);
  6. }
  7. });
  8. return {
  9. newInstance: function(options) {
  10. return new Events(options);
  11. }
  12. };
  13. })();

92vpleto

92vpleto1#

当我在视图呈现方法中获取示例时,如何设置集合的url参数。
您应该能够在选项哈希中传递一个url:

  1. Collection.newInstance({url: "your url"});

字符串
但是...
若要初始化集合,需要传递模型数组,因此需要更改集合定义:

  1. Collection = (function(){
  2. var Events;
  3. Events = Backbone.Collection.extend({
  4. initialize: function(models, options){
  5. this.url = options.url;
  6. alert(this.url);
  7. }
  8. });
  9. return {
  10. newInstance : function(models, options) { return new Events(models, options); }
  11. };
  12. })();


我不知道你为什么要为你的集合建立一个动态的url。:/你可能想定义集合是针对哪个模型的...但是,你也可以通过选项传递它。

  1. Collection.newInstance([
  2. //array of models...
  3. ], {
  4. url: "meh"
  5. });

编辑:

如果您需要动态url,但它的大部分内容仍然相同,您可以将url定义为一个函数:

  1. Events = Backbone.Collection.extend({
  2. url: function(urlOptions) {
  3. return 'yourDomain/resources?'+ urlOptions; // just return the url as a string
  4. }
  5. });

jsfidle示例:

jsfiddle.net/sbjaz/13

展开查看全部

相关问题