Backbone.js 为创建和更新建模不同的 url? [英] Backbone.js Model different url for create and update?

查看:13
本文介绍了Backbone.js 为创建和更新建模不同的 url?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个主干模型,我创建了一个这样的模型实例:

lets say I have a Backbone Model and I create an instance of a model like this:

var User = Backbone.Model.extend({ ... });
var John = new User({ name : 'John', age : 33 });

我想知道当我使用 John.save() 时是否可以使用 John.save() 来定位 /user/create当我使用 John.fetch() 定位 /user/get 时,第二次 (update/PUT) 定位 /user/update> 当我使用 John.remove() 定位 /user/remove

I wonder if it is possible when I use John.save() to target /user/create when I use John.save() on second time (update/PUT) to target /user/update when I use John.fetch() to target /user/get and when I use John.remove() to target /user/remove

我知道我可以在每次触发任何方法之前定义 John.url 但我想知道它是否可以在不覆盖任何 Backbone 方法的情况下自动发生.

I know that I could define John.url each time before I trigger any method but I'm wondering if it could be happen automatically some how without overriding any Backbone method.

我知道我可以使用像 /user/handle 这样的 url 并根据请求方法 (GET/POST/PUT/DELETE) 处理请求,但我只是想知道是否有在 Backbone 中为每个操作设置不同 url 的方法.

I know that I could use one url like /user/handle and handle the request based on request method (GET/POST/PUT/DELETE) but I'm just wondering if there is a way to have different url per action in Backbone.

谢谢!

推荐答案

方法 .fetch(), .save()<Backbone.Model 上的 code>.destroy() 正在检查模型是否定义了 .sync(),如果是,它将被调用否则 Backbone.sync() 将被调用(参见链接源代码的最后几行).

Methods .fetch(), .save() and .destroy() on Backbone.Model are checking if the model has .sync() defined and if yes it will get called otherwise Backbone.sync() will get called (see the last lines of the linked source code).

所以解决方案之一是实现 .sync() 方法.

So one of the solutions is to implement .sync() method.

示例:

var User = Backbone.Model.extend({

  // ...

  methodToURL: {
    'read': '/user/get',
    'create': '/user/create',
    'update': '/user/update',
    'delete': '/user/remove'
  },

  sync: function(method, model, options) {
    options = options || {};
    options.url = model.methodToURL[method.toLowerCase()];

    return Backbone.sync.apply(this, arguments);
  }
}

这篇关于Backbone.js 为创建和更新建模不同的 url?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆