Backbone和Rails嵌套路由
我在rails中定义了以下路由:
resources :accounts do resources :transactions end
这导致url如下:
/accounts/123/transactions/1
有没有一种简单的方法可以将其映射到骨干模型设置?
通过在模型中嵌套集合,非常容易支持这一点,如下所示:
var Account = Backbone.Model.extend({ initialize: function() { this.transactions = new TransactionsCollection; this.transactions.url = '/account/' + this.id + '/transactions'; this.transactions.bind("reset", this.updateCounts); }, });
这实现了我想要的。
你可以在这里阅读更多相关信息: http : //documentcloud.github.com/backbone/#FAQ-nested
这可能不是一个简单的方法,但我认为最好的方法是使用url并将其设置为这样的函数:
var Transaction = Backbone.Model.extend({ url: function(){ var url = 'accounts/"+this.account_id+"/transactions'; if (this.id !== undefined){ url += "/"+this.id } return url; } });
或者也许在coffeescript中(因为它是主干+ rails):
class Transaction extends Backbone.Model url: -> url = "accounts/#{@account_id}/transactions" url += "/#{@id}" if @id != undefined url
哦,你可以做得更像这样(肯定有更深的嵌套,它更好):
var url = ["accounts", this.account_id, "transactions"] if (this.id !== undefined) url.push(this.id) return url.join("/")
AFAIK现在在骨干网中有url实用程序,对我来说痛苦不够,所以我会在其他库中搜索一个:)
Backbone不直接支持嵌套URL的创建。 您必须使用函数来动态计算嵌套对象的结果URL。 例如:
var Account = Backbone.Model.extend({ initialize: function() { this.transactions = new TransactionsCollection(); var self = this; this.transactions.url = function () {return self.url + self.id + '/transactions';}; // etc }, });
更多信息: http : //documentcloud.github.com/backbone/#FAQ-nested
只需定义您的模型的url或(如果您使用)您的集合,如下所示:
var MyModel = Backbone.Model.extend({ url: 'accounts/123/transactions' });
或动态:
mymodel.url = 'accounts/' + accountId + '/transactions';
以这种方式配置的那些模型或集合的所有模型现在将相应地生成它的后端URL。
详细信息:
型号: http : //documentcloud.github.com/backbone/#Model-url
收集: http : //documentcloud.github.com/backbone/#Collection-url