Backbone.js 从模型:主干内部设置urlRoot
我编写了以下代码:Backbone.js 从模型:主干内部设置urlRoot,backbone.js,Backbone.js,我编写了以下代码: var Parent = Backbone.Model.extend({ initialize: function() { console.log("this is parent's init function"); }, defaults: { name: "", id: 0 }, parentFetch: function() { this.set("urlRoot",
var Parent = Backbone.Model.extend({
initialize: function() {
console.log("this is parent's init function");
},
defaults: {
name: "",
id: 0
},
parentFetch: function() {
this.set("urlRoot", "/cgi-bin/yoman.pl");
console.log("debug output" + this.urlRoot + ":" + this.get("urlRoot"));
this.fetch({
arg: "her",
success: function() {
console.log("fetch success");
},
error: function() {
console.log("fetch error");
}
});
},
urlRoot: "/cgi-bin/hello1.pl"
});
$(document).ready(function() {
console.log("this is ready function");
var myParent = new Parent();
myParent.parentFetch();
});
在这里,我尝试实现parentFetch函数,在其中设置模型的这个.urlRoot变量。然而,由于某种原因,fetch使用了urlRoot的旧值,该值被设置为默认值
为什么这个.set(“urlRoot”,…)不改变它的值?
我还打印了控制台输出:
console.log("debug output" + this.urlRoot + ":" + this.get("urlRoot"));
输出显示:
调试输出/cgi-bin/hello1.pl:/cgi-bin/yoman.pl
这里有什么问题以及如何解决它?set()
用于设置模型的属性,如name
等。urlRoot
不是一个属性,因此set()
不能用于设置它
要设置它,只需像其他对象值一样指定它,即:
this.urlRoot = "/cgi-bin/yoman.pl";
而不是
this.set("urlRoot", "/cgi-bin/yoman.pl");
作为参考,如果您在示例中的模型中尝试this.get('urlRoot')
或this.attributes.urlRoot
,您会发现它们都返回“/cgi-bin/yoman.pl”
,因为您进行了set()
调用