微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/js/150873.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐