Glenn Curtis Glenn Curtis - 6 months ago 25
jQuery Question

Saving a JQuery sortable list with Backbone save?

My backbone code, see below, is working without any issues, it gets the data and displays / renders that data using an underscore template. I have also add a trigger event to the backbone code, so that it gets JQuery to sort the template data into a sortable list.

However I have tried to update my sortable list with an update callback, which is meant to take the updated order of my list, convert it to JSON data, then using; to save the data to my database.

My Backbone data ::

var AdminColModel = Backbone.Collection.extend({
url: '/Admin/GetMenuData'

var AdminEditMenu = Backbone.View.extend({
el: $(".page"),
render: function() {
var that = this;
var MyMenu = new AdminColModel();
success: function(MyMenu) {
var menutemp = _.template( $('script.MenuTemplate').html(), {MyMenu: MyMenu.toJSON() } );
that.trigger('MenuSortableList', that); <- fires my sort list!
} //End of render function

var MyMenu = new AdminEditMenu();
MyMenu.on('MenuSortableList', function(event) {
$( "#AdminChangeMenuOrder" ).sortable({
axis: 'y',
placeholder: 'AdminMenuChangeableList',
helper: "clone",
forcePlaceholderSize: true,
forceHelperSize: true,
cursor: "move",
update: function() {
var sortableLinks = $(".AdminMenuChangeableList");
var linkOrderData = $(sortableLinks).sortable('serialize');

Now this all works, apart from the code within the 'update' section call within the sortable call.

This is my underscore template,

<script class="MenuTemplate" type="text/template">
<section id="AdminChangeMenuOrder">
<% _.each(MyMenu, function(MyMenu) { %>
<div id="<%= %>" class="AdminMenuChangeableList"><%= MyMenu.title %> @ <%= MyMenu.path %> Current Level : <%= MyMenu.level %></div>
<% }); %>

Now the template works, but I have been doing some research and it looks like a lot of people, use
lists, is that what I should do with my template, is that easy to convert to a JSON object?

All help most welcome,




Ok, I have this all working now. First I had to convert the JQuery sortable list into JSON format, then set it up in a backbone model and save that model, I am not sure if this is the right way about doing it, but it does work.

Where is the 'update' section of my sortable list which is what I have change,

        update: function() {
            var i = 1;
            var Data = $(this).sortable('toArray');
            _.each(Data, function(Data) { 
                var UpdatedMenuList = new Backbone.Model({ id: Data, level: i++ });
                UpdatedMenuList.url = '/Admin/UpdateMenuData';

If anyone thinks this is wrong, then please let me know and how best to change my code.