开发者

Backbone.js: How do I identify the model of the parent view upon an event?

开发者 https://www.devze.com 2023-01-28 06:17 出处:网络
I have two collections instantiated: items and sections. Each section can have multiple items and each item can occur in more than one section.

I have two collections instantiated: items and sections.

Each section can have multiple items and each item can occur in more than one section.

When I add an item to a section I want to get the hash of that item and save it to an array attribute of the section. This array attribute is used to determine which items are displayed in each section.

So let's say that I have a ItemListModel with 100 items and I have a section with an 'items' attribute with the array [ item3_id_hash, item27_id_hash, item59_id_hash ]. When I display the SectionView, I first map those hash ids to the Items collection to get those objects and then I create an ItemsView that displays only those objects.

The problem I have is in identifying those Items upon creation and upon deletion so that I can get their ids and add/remove them from the section.item attribute array.

I can think of a hackish solution to identify the item upon addition by setting a global variable called parent. I want to avoid using globals however.

Removing is another matter entirely. When the user clicks the X to delete an item in the view, I can't figure out how I can either identify the parent Section's model, or at the very least identify its ID.

Example view:

  • Section_1
    • Item_1
    • Item_2
    • Item_3
  • Section_2
    • Item_4
    • Item_5
    • Item_6

If the user deletes Item_2 from the view, how can I get Section_1.model.get('id') so I can get the section_1 object and then remove the 'id' for开发者_StackOverflow中文版 Item_2 from the 'items' array attribute in Section_1

The only solution I can think of is passing the 'id' for Section_1 to the HTML view when I draw ItemsView for Section_1. This is hackish and fragile so I was trying to avoid it.

FYI: SectionListView instantiates one or more SectionsViews, each of which instantiate one ItemListView, which instantiates one or more ItemViews


You should always go back to the model. If you want to remove an item, then remove it from the model list and have the different view listen for the removal events.

So your section is observing the List remove event and act accordingly (either remove the element on the page or re-render it self completely).

Models and events (alternatively, routes) should be preferred to glue code in most situation.

I hope I understood your question.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号