实例化集合骨干

时间:2013-11-27 06:55:05

标签: backbone.js

我有一个路由器类,它实际上有视图和集合的单独哈希,如下所述。当我在视图渲染方法中获取实例时,如何设置集合的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]||{};}
          };

})();

收集班走到这里

    The Collection Class is defined like this

      The Collection Class

        Collection = (function(){

        var Events;

        Events = Backbone.Collection.extend({

              initialize: function(props){
              this.url = props.url;
              alert(this.url);
            }
        });

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

1 个答案:

答案 0 :(得分:1)

  

当我拍摄时,如何设置集合的url参数   视图渲染方法中的实例。

您应该能够在选项哈希中传递一个网址:

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

BUT。

要初始化集合,您需要传递一组模型,因此您需要更改集合定义:

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

修改

如果您需要动态网址,但大部分内容仍然相同,您可以将网址定义为函数:

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

jsfiddle示例:

jsfiddle.net/sbjaz/13