backbone.js 教程:url 方法如何工作?
教程: 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该行相当于
仅使用
return base+'/'+this.id
会导致base="documents/"< 模型的 url 为“documents//6” /code> 和
id=6
更新
正如 Adam Lassek 在评论中提到的那样,该行应该像
本示例一样简单地编写,因为
base
变量是在同一块中定义的。然而,这行代码也在backbone.js源代码 其目的如上所述。您应该在模型中设置
urlRoot
属性,而不是重写url
方法:That line is the equivalent of
just having
return base+'/'+this.id
would result in a url of "documents//6" for a model withbase="documents/"
andid=6
Update
As Adam Lassek mentioned in the comments, that line of should simply be written as
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 theurlRoot
attribute in the model: