Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js - Insert new view item in order

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?

like image 248
Joe Avatar asked Feb 11 '12 16:02

Joe


1 Answers

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).

like image 117
mna Avatar answered Oct 07 '22 05:10

mna