0

我有点坚持尝试获取 Backbone 集合,我是 Backbone 的新手,我确信我错过了一些简单的东西,但不知道是什么。

有什么想法吗?

$ ->


User = Backbone.Model.extend(
    urlRoot: "/users"
    )
  user = new User()

  View = Backbone.View.extend(
    tagName: "li"
    el: "ul"
    id: "#users"
    template: _.template("<li>...just a code...<span class='buttons'><button class='info'>Info</button><button class='delete'>Delete</button></span></li>")
    render: -> 
      @$el.html(@template())
    )



view = new View(
    model: user
    )
  view.render().el

  Users = Backbone.Collection.extend(
    model: User
    url: "/users"
    parse: (resp, xhr) ->
      return resp.toJSON()
    )



usersCollection = new Users() 
  usersCollection.fetch(
    success: (response) ->
      console.log 'success'
      console.log usersCollection
      console.log response
    error: (data, response) ->
      console.log(response)
    )

我的 "/users/ 返回这个数组:

[{"created_at":"2013-05-25T18:00:43Z","email":"user1@mail.ru","id":1,"updated_at":"2013-05-25T18:00:43Z"},{"created_at":"2013-05-25T18:00:43Z","email":"user2@mail.ru","id":2,"updated_at":"2013-05-25T18:00:43Z"},{"created_at":"2013-05-25T18:00:43Z","email":"user3@mail.ru","id":3,"updated_at":"2013-05-25T18:00:43Z"},{"created_at":"2013-05-25T18:00:43Z","email":"user4@mail.ru","id":4,"updated_at":"2013-05-25T18:00:43Z"},{"created_at":"2013-05-25T18:00:43Z","email":"user5@mail.ru","id":5,"updated_at":"2013-05-25T18:00:43Z"},{"created_at":"2013-05-25T18:00:43Z","email":"user6@mail.ru","id":6,"updated_at":"2013-05-25T18:00:43Z"},{"created_at":"2013-05-25T18:00:43Z","email":"user7@mail.ru","id":7,"updated_at":"2013-05-25T18:00:43Z"}]

控制器(Ruby on Rails)看起来像这样:

  def index
    users = User.all
    render json: users, status: 200
  end

在 console.log 我有:

success
child {length: 1, models: Array[1], _byId: Object, constructor: function, model: function…}
4

2 回答 2

1

尝试在您的视图定义中添加一个初始化属性,并在集合重置时使用“listenTo”将事件绑定到对象(例如):

View = Backbone.View.extend(
    tagName: "li"
    el: "ul"
    initialize: function(){
        this.collection = new app.YourCollection();
        this.collection.fetch({ reset: true });

        this.listenTo(this.collection, 'reset', this.render);
    },

然后在渲染属性上(本例中的方法):

render: function(){
        this.collection.each(function(item){
            this.renderWeeklyMenu(item);
        }, this);
    },

renderItem: function(item){
        var itemView = new app.itemView({
            model : item
        });
        this.$el.append(itemView.render().el);
    }

并且“获取”返回 JSON 数据,因此您不需要:

parse: (resp, xhr) ->
      return resp.toJSON()
    )

希望这可以帮助。

于 2016-10-31T10:45:02.827 回答
0

删除您的parse函数,因为您的响应是默认情况下主干所期望的格式。它将正确解析 JSON 并将数组视为数据对象的集合,这些数据对象将被转换为模型实例。

因此,您的 fetch 工作正常,但您不正确 A)在视图中包含来自您的集合或模型的任何数据(因此您无法轻松查看它是否正常工作,并且 B)在加载视图后使用数据重新渲染视图绑定到集合的sync事件。

于 2013-05-26T07:20:04.257 回答