Backbone.js - insert a new element in the form

I use very similar code for the Backbone ToDo example - http://documentcloud.github.com/backbone/docs/todos.html .

After entering a new collection into the collection, I sort the collection. The todo example adds 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 in the collection, and not just in the last place. Any idea how to do this?

+4
source share
1 answer

First get the index of the newly added model in the collection (after sorting). You can get it using the underscore method indexOf ie index = todoColl.indexOf(todo); .

Then use the selector: eq () jQuery to get the element currently at that position in the list and .before () your new element, i.e. $("li:eq(" + index.toString() + ")").before(view.render().el); (provided that the representation displays the element li). Caution, add code to control the case if the last element is the last (in this case, the jQuery selector will be empty).

+6
source

Source: https://habr.com/ru/post/1395936/


All Articles