javascript – Backbone set collection属性(用于url)

我需要将一个id传递给一个集合以便在url中使用(例如/user/1234/projects.json),但我不知道如何做到这一点,一个例子会很精彩.

我的应用程序结构的方式是在启动时拉出并呈现“用户”的集合,然后我想在单击用户时将他们的“文档”从服务器拉到新集合中并在新视图中呈现.问题是将用户标识放入文档集合中以提供documents.fetch()的相关URL.

我想我已经知道了,这是一个例子:

//in the the view initialize function     
  this.collection = new Docs();
  this.collection.project_id = this.options.project_id;
  this.collection.fetch();

  //in the collection
  url: function() {
     return '/project/api/' +this.project_id+'/docs';
  }

解决方法

您的用户集合网址应设置为/ user.一旦设置完毕,你的模型应该利用该网址来实现他们的魔力.我相信(并非完全正面)如果模型在集合中,调用’url’方法将返回/ user /:id.因此,所有典型的REST-ish功能都将用于’/ user /:id’.如果你试图用关系做某事(用户有很多文件),那就是冲洗和重复.那么,对于您的文档集合(这对用户来说是否正确?),您需要将URL设置为“user_instance.url / documents”.

显示与骨干模型的一对多关系,您可以执行以下操作(针对urlRoot升级到主干0.5.1):

var User = Backbone.Model.extend({
    initialize: function() {
        // note,you are passing the function url.  This is important if you are
        // creating a new user that's not been sync'd to the server yet.  If you
        // did something like: {user_url: this.url()} it wouldn't contain the id
        // yet... and any sync through docs would fail... even if you sync'd the
        // user model!
        this.docs = new Docs([],{user_url: this.url});
    },urlRoot: '/user'
});

var Doc  = Backbone.Model.extend();

var Docs = Backbone.Collection.extend({
    initialize: function(models,args) {
        this.url = function() { args.user_url() + '/documents'; };
    }
});

var user = new User([{id: 1234}]);
user.docs.fetch({ success: function() { alert('win') });

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...