【问题标题】:Backbone.js with a custom fetch URL带有自定义获取 URL 的 Backbone.js
【发布时间】:2013-08-22 14:24:17
【问题描述】:

我正在尝试在我的主干模型上设置一个变体获取方法,该方法将为给定用户获取当前模型。这可从/api/mealplans/owner/{username}/current 上的 API 获得。

我编写了以下模型。我注释掉了 URL Root,因为原型 fetch 调用只是使用 urlRoot,我想看看它是否覆盖了我以某种方式传入的 url 参数。

var mealPlan = Backbone.Model.extend({
  name: 'Meal Plan',
  //urlRoot: '/api/mealplans',
  defaults: {},
  fetchCurrent: function (username, attributes, options) {
    attributes = attributes || {};
    options = options || {};
    if (options.url === undefined) {
      options.url = "/api/mealplans/owner/" + username + "/current";
    }
    return Backbone.Model.prototype.fetch.call(this, attributes, options);
  },
  validate: function (attributes) {
    // To be done
    return null;
  }
});

我已经在其他地方看到了这种情况,例如backbone.js use different urls for model save and fetch - 在这种情况下,代码略有不同(我从它开始并将其分解以使我更容易阅读。 )

当我将选项对象传递给 fetch 时,它的 url 参数很好,但它似乎忽略了它!

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

    我假设获取与保存相同的参数 - 事实并非如此。

    fetch 的方法签名只接受“options”而不是“attributes”,因此找不到 url 参数。

    模型代码应该看起来更像这样..

       var mealPlan = Ministry.Model.extend({
    
            name: 'Meal Plan',
            urlRoot: '/api/mealplans',
    
            defaults: {
            },
    
            fetchCurrent: function (username, options) {
                options = options || {};
                if (options.url === undefined) {
                    options.url = this.urlRoot + "/owner/" + username + "/current";
                }
    
                return Backbone.Model.prototype.fetch.call(this, options);
            },
    
            validate: function (attributes) {
                // To be done
                return null;
            }
        });
    

    【讨论】:

    • 我为这个答案搜索了 100 个主题、问题和帖子!非常感谢!
    • 不用担心 - 如果我自己发现问题,我总是会尝试回答我发布的问题,以防万一。我有时会发疯地浏览未答复的在线帖子。
    【解决方案2】:

    我认为最好重写 url() 方法,如下所示:

     var mealPlan = Ministry.Model.extend({
    
        name: 'Meal Plan',
        urlRoot: '/api/mealplans',
    
        //--> this gets called each time fetch() builds its url
        url: function () { 
            //call the parent url()
            var url=Backbone.Model.prototype.url.call(this);
            //here you can transform the url the way you need
            url += "?code=xxxx";
            return url;
        }
     ...
    

    此外,在您上面的示例中,我认为有一个错误,您应该将 fetchCurrent 替换为 fetch

    【讨论】:

    • 应该在覆盖中提及 urlRoot 吗?目前尚不清楚根是如何附加到“?code=xxxx”字符串的。也许var url=Backbone.Model.prototype.urlRoot.call(this);
    • 不,它是来自模型的方法。正确的方法是 url.call()。如果您查看源代码,您会看到正确的属性:backbonejs.org/docs/backbone.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 2012-01-11
    • 1970-01-01
    • 2011-10-03
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多