骨干提取不起作用

时间:2013-05-26 06:58:49

标签: ruby-on-rails ruby-on-rails-3 backbone.js

我对尝试获取Backbone Colection有点困惑,我是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…}

2 个答案:

答案 0 :(得分:1)

尝试在View定义中添加initialize属性,并使用&#34; listenTo&#34;将事件绑定到对象。当集合重置时(例如):

a b c

1 2 3

然后在render属性(本例中的方法):

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

&#34; fetch&#34;返回JSON数据,因此您不需要:

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

希望这有帮助。

答案 1 :(得分:0)

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

所以你的fetch工作正常,但你没有正确A)包括你的视图中的任何数据或视图中的模型(所以你不能轻易看出它是否正常工作而且B)用以后的数据重新渲染视图它通过绑定到集合的sync事件来加载。