Backbone.js的型号不同的URL进行创建和更新? [英] Backbone.js Model different url for create and update?
问题描述
可以说我有一个骨干示范和我创建这样一个模型的实例:
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()
在第二次(更新/ PUT)目标当我使用/用户/更新
John.fetch()
目标 /用户/ GET
键,当我使用 John.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
每次定义,但我想知道,如果它可以自动发生一些如何不覆盖任何方法骨干
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.
我知道,我可以用一个URL像 /用户/句柄
和处理请求只是不知道是否有一种方法可以在每骨干作用不同的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.
谢谢!
推荐答案
方法<一href=\"http://documentcloud.github.com/backbone/docs/backbone.html#section-40\"><$c$c>.fetch()$c$c>, <一href=\"http://documentcloud.github.com/backbone/docs/backbone.html#section-41\"><$c$c>.save()$c$c>和<一个href=\"http://documentcloud.github.com/backbone/docs/backbone.html#section-42\"><$c$c>.destroy()$c$c>在 Backbone.Model
正在检查如果模型具有 .SYNC()
定义,如果是的,它会被调用,否则 Backbone.sync()
将调用(见链接的源$ C $ c最后行)。
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屋!