I am using very similar code to the Backbone ToDo example - http://documentcloud.github.com/backbone/docs/todos.html.
After I insert a new model into the collection, I sort the collection. The todo example appends the new data to the end of the view
var view = new TodoView({model: todo});
$("#todo-list").append(view.render().el);
I want to insert my model data into the view according to its position within the collection and not merely to last place. Any idea how to do this?
First get the index of the newly added model in the collection (after the sort ). You can get it with the underscore method indexOf
i.e. index = todoColl.indexOf(todo);
.
Then use the :eq() jQuery selector to get the item currently at this position in the list, and .before() your new item, i.e. $("li:eq(" + index.toString() + ")").before(view.render().el);
(assuming the view renders a li element). Careful, add code to manage the case if the new item is last (in which case the jQuery selector will be empty).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With