使用 Backbone.js 加载模型关系
我正在使用 Rails REST 后端编写我的第一个 Backbone.js 应用程序,令我困惑的一件事是模型之间的关系。
我正在编写的这个应用程序将以 Ticket
和 Client
作为模型。我还设置了 Tickets
和 Clients
集合。
事实证明,我有几千个客户,我不想将它们加载到内存中,而是想在票证引用客户时延迟加载客户。
我尝试了一种非常幼稚的方法,但显然行不通,因为 Model#fetch() 方法是异步的。
到目前为止,这是我的 Ticket 模型(在 CoffeeScript 中):
class Deputy.Models.Ticket extends Backbone.Model
initialize: ->
@fetchClient()
fetchClient: ->
@client = new Deputy.Models.Client()
@client.set id: @get('userid')
@client.fetch()
clientName: ->
first = @client.get('firstname')
last = @client.get('lastname')
"#{first} #{last}"
正如您可以想象的,clientName()
函数始终返回“undefined undefined”,因为当已拨打电话。
处理这种数据关系的正确方法是什么?请注意,如果您退一步说我使用了错误的方法并向我提出建议,我不介意。
任何指示、文章或其他任何东西都将不胜感激。
I am writing my first Backbone.js app with a Rails REST backend, and one thing that is puzzling me is the relationship between models.
This app that I am writing will have Ticket
and Client
as models. I have setup both Tickets
and Clients
collections as well.
It turns out I have a few thousand customers and I wouldn't like to load them in memory, instead I'd like to lazily load the customer when a ticket refers to it.
I have tried a very naive approach that obviously doesn't work because Model#fetch()
method is asynchronous.
Here's my Ticket model so far (in CoffeeScript):
class Deputy.Models.Ticket extends Backbone.Model
initialize: ->
@fetchClient()
fetchClient: ->
@client = new Deputy.Models.Client()
@client.set id: @get('userid')
@client.fetch()
clientName: ->
first = @client.get('firstname')
last = @client.get('lastname')
"#{first} #{last}"
As you can imagine, the clientName()
function always returns "undefined undefined", because fetch didn't return when the call is made.
What is the right way of handling this kinds of data relationship? Please note that I don't mind if you take a step back and say I am using the wrong approach and suggest me something instead.
Any pointers, articles, or anything else would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
client.fetch()
接受一个success
选项,该选项将在完成时触发。当您触发 fetchClient 时,您应该添加加载 UI(可能就像用旋转图标替换按钮一样简单),并且当客户端完成加载时继续显示名称。在 JavaScript 中你会做这样的事情:
client.fetch()
accepts asuccess
option that will be fired upon completion. When you firefetchClient
you should add loading UI (could be something as simple as replacing a button with a spinning icon) and when the client finishes loading continue displaying the name.In JavaScript you would do something like this: