示例化集合 Backbone.js

li9yvcax  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(123)

我有一个路由器类,它实际上为视图和集合提供了单独的哈希值,如下所述。当我在视图呈现方法中获取示例时,如何设置集合的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 = (function() {
    var Events = Backbone.Collection.extend({
        initialize: function(props) {
            this.url = props.url;
            alert(this.url);
        }
    });

    return {
        newInstance: function(options) {
            return new Events(options);
        }
    };
})();

92vpleto

92vpleto1#

当我在视图呈现方法中获取示例时,如何设置集合的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); }
  };
})();


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

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
  }
});

jsfidle示例:

jsfiddle.net/sbjaz/13

相关问题