如何协调BackboneJ的视图并在它们之间传递对象

How to coordinate BackboneJs views and pass objects between them?

本文关键字:之间 对象 视图 何协调 协调 BackboneJ      更新时间:2024-02-06

我有一个BackboneJs应用程序,下面是它的文件结构

|-- collections
|   |-- customers.js
...
|-- models
|   |-- customer.js
...
|-- views
|   |-- customer
|   |   |-- create.js
|   |   |-- edit.js
|   |   |-- list.js
...

|-- templates
|   |-- customers
|   |   |-- create.html
|   |   |-- edit.html
|   |   |-- list.html
...

工作代码流

views/customer/list视图的initialize函数中,客户集合(collections/customers)由this.collection.fetch获取。当从服务器获取customers集合后渲染完成时,我在html表中显示了一个customers列表。

当用户单击表行中的"编辑"按钮时,会触发一个事件。该事件的目的是加载customer/edit视图,以便用户可以更新表中选定的客户。

这是通过Backbone.history.navigate('#customers' + customerId, {trigger:true})完成的。然后发生了一条路由,并调用了/api/customers/{customerId}

摘要

这个结构没有问题,它按预期工作。但我认为没有必要去服务器获取客户的详细信息,因为views/customers/list中的collection具有整个客户对象。我可以得到如下所选的var selectedCustomer = this.collection.get(selectedCustomerId)

问题

我的问题是如何将selectedCustomer对象传递到views/edit视图,并消除获取客户详细信息的服务器调用。此外,加载views/customer/edit视图时,散列应更改为#customers/{customerId}

我会考虑更改您的应用程序流。与其从listView中获取集合,不如从路由器中获取集合并将其传递给listView。然后,当路由器调用editView时,您也可以将集合传递给editView,而无需再次获取。那么,只需要从您的editView呼叫this.collection.get(selectedCustomerId)即可。希望这能回答您的问题,但如果没有更好地查看您的代码,我将无法提供更多帮助。