【问题标题】:Backbone fetch - "url" property or function must be specified error主干提取 - 必须指定“url”属性或函数错误
【发布时间】:2017-03-04 12:32:18
【问题描述】:

对 Backbone 还很陌生,所以请注意我的无知...

我有一个简单的 GallereyModel:

var GalleryModel = Backbone.Model.extend({
    defaults : {
        id: "",
        width: ""
    },
    url : ""
});

模型更新时,调用函数galleryModelUpdate

var GalleryView = Backbone.View.extend({

initialize: function () {
    this.listenTo(this.model, "change", this.galleryModelUpdate);
},
galleryModelUpdate: function(){
    console.log("updated gallery model"+this.model.get("id");
    if (this.model.get("url")){  
        console.log("fetching " + this.model.get("url")); // this line prints with the correct url
        this.model.fetch({ // this line gives error
            success: function(){
                console.log("fetched succesfully!");
            }
        });
    }
}

});

我在调用 fetch 之前在模型上打印 url 的值,所以不知道为什么会抛出“url”未定义错误?

非常感谢您提前提供的帮助

【问题讨论】:

  • 但您没有在 fetch 中设置 url - this.model.fetch({ url: this.model.get("url"), success: function(){ console.log("fetched succesfully!"); } });
  • 哦,我明白了。我的印象是fetch 调用会自动在模型中查找url。谢谢,问题解决了
  • Backbone 将查看 url property 而不是 attribute。您的 url: "" 是属性,this.model.get('url') 是属性但它们不相关:stackoverflow.com/a/39820057/479863

标签: javascript backbone.js


【解决方案1】:

需要定义 urlurlRoot 模型属性才能获取模型。 您可以将模型 url 设置为指向 url 数据属性:

Backbone.Model.extend({
  url: function () {
    return this.get('url');
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    相关资源
    最近更新 更多