运维开发网
广告位招商联系QQ:123077622
 
广告位招商联系QQ:123077622

ruby-on-rails-3 – Backbone.js集合网址

运维开发网 https://www.qedev.com 2020-08-09 09:13 出处:网络 作者:运维开发网整理
我正在使用rails api开发一个backbone.js应用程序,它提供了如下所示的json: [{ "title": "Da vinci Code", "price": "50" }, { "title": "Some other name", "price": "45" }], 去做: >当用户访问网址“
我正在使用rails api开发一个backbone.js应用程序,它提供了如下所示的json:

[{
        "title": "Da vinci Code",
        "price": "50"
    },
    {
        "title": "Some other name",
        "price": "45"
    }],

去做:

>当用户访问网址“www.backboneapp.com/authors/1”时,它应显示属于作者的书籍列表.

进展:

  – 服务器端-Rails [authorscontroller #show]

def show
  @author = Author.find(params[:id])
  @books  = @author.books
  respond_to do |format|
    format.json { render :json => @books }
    format.html
  end
end

2.Client侧-Backbone.js的

路由器:

routes: {
  'authors/:id': 'showauthor'
},

showauthor: function(id) {

  $('#container').empty();
  window.available_books = new AvailableBookList({
    id: id
  });

  this.availablebooklistview = new AvailableBookListView({
    id: id,
    collection:  available_books
  });

  $('#container').append(this.availablebooklistview.render().el);
}

AvailableBookList Collection:

AvailableBookList = Backbone.Collection.extend({
  model: AvailableBook,
  url: "/authors/" + this.id  
})

查看部分:

$(document).ready(function(){

AvailableBookListView = Backbone.View.extend({
  tagName:   'section',
  className: 'availablebooklist',

  initialize: function() {
    _.bindAll(this, 'render');
    this.collection.bind('reset', this.render);
  },

  render: function() {
    this.collection.each(function(available_book) {
      var view = new AvailableBookView({
         model: available_book,
      });

      this.$('.availablebooklist').append(view.render().el);
    });
    return this;
  }
});

});

问题:当我访问“www.backboneapp.com/authors/1”时,我收到404错误.

在console.log中显示:

   获取:www.backboneapp.com/authors/undefined

在Rails日志中:参数{id =>未定义}

*我哪里错了? *

任何帮助和建议都非常感谢

我将假设您并不是指路由器中的新AuthorList,而是新的AvailableBookList.

您的收藏中有两个问题:

>在您的网址定义中,这指的是窗口对象.

>您在构造函数中传递的id参数未应用于您的集合实例.它仅适用于视图(不适用于模型或集合).

要解决第一个问题,您可以使用函数来定义集合URL,这将使您进入正确的范围:

AvailableBookList = Backbone.Collection.extend({
  model: AvailableBook,
  url: function() {
    return "/authors/" + this.id;
  }
});

对于第二个,您可以定义一个初始化函数并在其中设置id属性:

AvailableBookList = Backbone.Collection.extend({
  initialize: function(models, options) {
    this.id = options.id;
  },
  model: AvailableBook,
  url: function() {
    return "/authors/" + this.id;
  }
});

出于可读性目的,我还建议将id重命名为author_id:

AvailableBookList = Backbone.Collection.extend({
  initialize: function(models, options) {
    this.author_id = options.author_id;
  },
  model: AvailableBook,
  url: function() {
    return "/authors/" + this.author_id;
  }
});

更新

您还以错误的方式初始化您的收藏.根据Backbone.js source,构造函数签名是模型,选项:

window.available_books = new AvailableBookList(null, {
  id: id
});

扫码领视频副本.gif

0

精彩评论

暂无评论...
验证码 换一张
取 消