backbone.js 教程:url 方法如何工作?

发布于 2024-12-15 08:33:40 字数 896 浏览 0 评论 0原文

教程: http://www.jamesyu.org/2011/01/27/cloudedit-a-backbone-js-tutorial-by-example/" rel="nofollow"> jamesyu.org/2011/01/27/cloudedit-a-backbone-js-tutorial-by-example/ 我正在浏览 CloudEdit Rails/backbone.js 教程,并被困在第一块代码上。这是:

var Document = Backbone.Model.extend({
  url : function() {
    var base = 'documents';
    if (this.isNew()) return base;
    return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id;
  }
});

我正在努力解决的问题是

return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id;

因为 base = 'documents' 不是 base.charAt(base.length - 1) = s ? 我知道它应该做什么,我只是想知道它为什么这样做。 base 的值有时会更改为 documents/ 吗?为什么不直接写return base+'/'+this.id

tutorial: http://www.jamesyu.org/2011/01/27/cloudedit-a-backbone-js-tutorial-by-example/
I am going through the CloudEdit rails/backbone.js tutrorial and got stuck on the very first chunk of code. here it is:

var Document = Backbone.Model.extend({
  url : function() {
    var base = 'documents';
    if (this.isNew()) return base;
    return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id;
  }
});

the line I am struggling with is this

return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id;

Since base = 'documents' isn't base.charAt(base.length - 1) = s ?
I know what it is supposed to do, I am just wondering why it does it. Does the value of base change to documents/ sometimes? Why not just write return base+'/'+this.id

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

对你再特殊 2024-12-22 08:33:40

该行相当于

if last character is '/'
   return base + this.id
else 
   return base + '/' + this.id

仅使用 return base+'/'+this.id 会导致 base="documents/"< 模型的 url 为“documents//6” /code> 和 id=6

更新
正如 Adam Lassek 在评论中提到的那样,该行应该像

return base+'/'+this.id

本示例一样简单地编写,因为 base 变量是在同一块中定义的。然而,这行代码也在backbone.js源代码 其目的如上所述。

您应该在模型中设置 urlRoot 属性,而不是重写 url 方法:

var Document = Backbone.Model.extend({
  urlRoot : 'documents'
});

That line is the equivalent of

if last character is '/'
   return base + this.id
else 
   return base + '/' + this.id

just having return base+'/'+this.id would result in a url of "documents//6" for a model with base="documents/" and id=6

Update
As Adam Lassek mentioned in the comments, that line of should simply be written as

return base+'/'+this.id

for this example as the base variable is defined in that same block. However that line of code is also in the backbone.js source code and its purpose is as described above.

Instead of overriding the url method you should set the urlRoot attribute in the model:

var Document = Backbone.Model.extend({
  urlRoot : 'documents'
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文