What is the best way to change data in a model?
Imagine a list with some items. Each item is a movie and includes:
- the title
- a ranking with stars (1-5)
- add to my list button
- a textbox that you might leave a comment
How might b开发者_开发百科e done:
A) The item will listen for the buttonClicked event and then will call a method on the model:
onClick: function(event){ this.model.addToMyList(); }
there is no need to specify the movieId because the "model" is for this item. In the other cases the model is for all the items.
B The list will listen for an item to dispatch the buttonClicked event, gets data from the event and will call a method on a model:
model.addToMyList(movieId)
C The list will listen for an item to dispatch the buttonClicked event, this event will carry on the index(that is not the id of the movie) of the item, then finds the movieId using the index on the list and will call a method on a model:
model.addToMyList(movieId)
You don't mention any languages so I'm going to give a language neutral response.
Don't recommend C: Identifying an item by the index in a list might seem an easy option but any extension functionality or maintainability could get messy later (suddenly ordering a list, having users filter the list etc).
With maintainability in mind (not pre-emptive design but design that'll be more accommodating to changes), it's best for the event handler to be able to identify what's being handled. That way, you could modify the handler that will apply for all items.
With B: I'd more reserve that for a collection that changes, with the intention that controls/components are listening for a collection change (such as INotifyCollectionChangedin .net). So it's a difficult thing to say not knowing whether there's specific actions you want to do with this collection but it wouldn't be my first choice unless the collection (as a data model) change determines other aspects.
So with the above in mind, (this will sound like an A-B hybrid but its a commonly used solution): new items created are signed up to an event handler (just code one event handler), and pass in either the reference to the item-row itself or an identifier. So, if its possible, you'd be looking at:
onClick: function(MyEvent e)
{
this.model.addToMyList(e); //or this.model.addToMyList(e.ID)
}
So you have multiple items signing up for the same event, one event handler to maintain and the ability to preserver that handling should your list be changed through filters, sorting etc.
精彩评论