BackboneJS model.url 使用 collection.url [英] BackboneJS model.url using collection.url

查看:16
本文介绍了BackboneJS model.url 使用 collection.url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的理解,Backbone JS 模型的默认行为是返回集合的 URL,除非该模型指定了 urlRoot.我似乎无法让这种行为起作用.

From my understanding the default behavior of Backbone JS Models are to return the Collection's URL, unless the model has a urlRoot specified. I can't seem to get the behavior to work.

来自文档:

model.url() ... 默认情况下生成以下形式的 URL:[collection.url]/[id]",但如果不应将模型的集合纳入其中,您可以通过指定显式 urlRoot 进行覆盖帐户.

model.url() ... Generates URLs of the form: "[collection.url]/[id]" by default, but you may override by specifying an explicit urlRoot if the model's collection shouldn't be taken into account.

这里分别是我的收藏和模型:

Here is my collection, and model respectively:

var MyCollection = Backbone.Collection.extend({
    model: Model,
    initialize: function(options){
        this.options = options || {};
    },
    url: function(){
        return "/theurl/" + this.options.param;
    }
});
return MyCollection;

...

var MyModel = Backbone.Model.extend({
    urlRoot: '/theurl',
    initialize: function() {
    }
});
return MyModel;

当一个模型在没有集合的情况下加载时,它工作得很好并提交到/theurl,但是当它加载到集合中时,所有方法都提交到/theurl/param/.

When a model is loaded without a collection, it works great and submits to /theurl, but when it's loaded into a collection, all methods submit to /theurl/param/.

如果我正确理解文档,模型的 urlRoot 应该覆盖这个行为;即便如此,模型 url 应该是 /theurl/param/{MODEL-ID}.

If I'm understanding the documentation correctly, the urlRoot of the Model should override this behavior; and even then the models url should be /theurl/param/{MODEL-ID}.

对我遗漏/误解的任何想法?

Any ideas on what I'm missing/misunderstanding?

...

PS:集合中的model:Model是通过RequireJS引入的

PS: The model: Model from the collection is brought in via RequireJS

推荐答案

即使您指定了 urlRoot,它也将始终使用集合的 url.

It will always use the collection's url even if you have urlRoot specified.

urlRoot 的原因是你可以在覆盖中使用它,或者如果模型碰巧不在集合中(例如它可能被删除,但仍然存在于客户端上).

The reason for urlRoot is so you can use it in an override, or if the model happens to not be in a collection ( for example maybe it gets removed, but still exists on the client).

因此,如果您想 fetchsave 模型并覆盖由集合生成的 url,则需要传递 urlRoot将这些方法明确作为一个选项.例如:

So if you want to fetch or save the model and override the url generated by the collection you'll need to pass the urlRoot into these methods explicitly as an option. For example:

yourModel.save({ url: yourModel.urlRoot });

我同意文档令人困惑,这最近也引起了我的注意.

I agree the documentation is confusing and this caught me out recently too.

这篇关于BackboneJS model.url 使用 collection.url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆