从模型内部设置urlRoot:backbone

时间:2013-06-11 10:49:05

标签: 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", "/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函数,我在其中设置模型的this.urlRoot变量。但是,由于某种原因,fetch使用urlRoot的旧值,该值设置为默认值。

为什么this.set(“urlRoot”,...)不会改变它的值? 我也打印到控制台输出:

console.log("debug output" + this.urlRoot + ":" + this.get("urlRoot"));

输出结果显示: debug output / cgi-bin / hello1.pl:/cgi-bin/yoman.pl

这里有什么问题以及如何解决?

1 个答案:

答案 0 :(得分:3)

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()打电话给您制成。

相关问题