1

我最近一直在尝试 Backbone,并且有一个非常基本的问题。

我需要搜索不同类型的记录,搜索 API 返回一个 JSON 响应,例如

{ foo: 
  [
      { name: 'foo1', url: '/foo1' },
      { name: 'foo2', url: '/foo2' }
  ],
  bar:
  [ { name: 'bar1', url: '/bar1' } ],
  baz:
  [ { name: 'baz1', url: '/baz1' } ]
}

我有一个 Foo、Bar 和 Baz 的骨干模型。获取时应该访问我的服务器并为我获取搜索结果的集合。我尝试过类似的事情

window.searchEntities = Backbone.Collection.extend({
  url: '/get_search_results'

  model: function(attrs, options) {
    //Typecast the JSON to Foo, Bar and Baz Models
  });      
});

但是,我不知道如何解析服务器返回的结果,以便我的集合包含模型 Foo、Bar 和 Baz?或者我应该调整服务器返回的结果,以便使用 Backbone 更容易处理?

4

1 回答 1

0

As I'm seeing your JSON is not returning 3 different Models but 3 different Collection due the 3 of them are containing Arrays.

I think you should start from the beginning, If I understood weel you want to return a bunch of Models of different type, let's say:

[
  {
    type: "Foo",
    name: "foo1",
    url: "/foo1"
  },

  {
    type: "Foo",
    name: "foo2",
    url: "/foo2"
  },

  {
    type: "Bar",
    name: "bar1",
    url: "/bar1"
  },

  {
    type: "Baz",
    name: "baz1",
    url: "/baz1"
  },
]

I see a Collection there, and also different Models of different types.

Now let's see the SearchCollection, I don't think you can play with the model property like you show in your example, so let's say all the Models has a common Model parent Result:

window.SearchEntities = Backbone.Collection.extend({
  url: '/get_search_results'

  model: Result  
});

From here we can do it simple and don't create sub-classes of Result if there is not a real need for it:

window.Result = Backbone.Model.extend({
  initialize: function(){
    this.url = this.get( "url" );
  }
});

And you're done:

var searchEntities = new window.SearchEntities();
searchEntities.fetch();

// ... wait for the fetch ends

searchEntities.at(0).get( "type" ); //=> "Foo"

Still I don't feel confortable by two reasons:

  • I don't see clear why you want to play with the Result.url.
  • Where are the ids of your Models? which are very important for Backbone.
于 2012-08-14T19:31:33.720 回答