2011-11-16 9 views
6

Todavía estoy encontrando mi camino con Backbone y siempre he usado Prototype en lugar de jQuery en el pasado, así que por favor, perdónenme si estoy haciendo algo estúpido.Listas ordenadas jQuery vinculadas y colecciones de Backbone

Estoy tratando de desarrollar una interfaz de usuario que contenga varias listas desordenadas conectadas donde cada lista sortable está representada por una colección Backbone independiente. Estoy usando las plantillas ICanHaz y Moustache, pero eso no es importante para mi pregunta.

Al arrastrar elementos entre las listas, ¿cómo conseguiría la actualización automática de las colecciones (eliminar un modelo de uno e insertarlo en otro)? Actualmente estoy tratando de utilizar los métodos de recepción y eliminación en la interacción ordenable de jQueryUI. ¿Estoy al menos en la línea correcta?

var WS = {}; 

(function(ns) { 
    ns.Item = Backbone.Model.extend(); 

    ns.Content = Backbone.Collection.extend({ 
     model: ns.Item, 
     url: location.href, 
     initialize: function(el) { 
      this.el = $(el); 
      this.deferred = this.fetch(); 
     }, 
     recalculate: function() { 
      var count = this.length; 
      this.el.next(".subtotal").html(count); 
     }, 
     setOrder: function() { 
      $.ajax({ 
       url: this.url + "/reorder", 
       type: "POST", 
       data: "tasks=" + $(this.el).attr("id") + "&" + this.el.sortable("serialize") 
      }); 
     } 
    }); 

    ns.ContentRow = Backbone.View.extend({ 
     tagName: "li", 
     className: "item", 
     events: { 
      "click .delete": "destroy" 
     }, 
     initialize: function(options) { 
      _.bindAll(this, "render", "destroy"); 
      this.model.bind("change", this.render); 
      this.model.view = this; 
     }, 
     render: function() { 
      var row = ich.item(this.model.toJSON()); 
      $(this.el).html(row); 
      return this; 
     }, 
     destroy: function() { 
      if (confirm("Really delete?")) { 
       this.model.destroy({ 
        success: function(model, response) { 
         $(model.view.el).remove(); 
        }, 
        error: function(model, response) { 
         console.log(response); 
        } 
       }); 
      } 
     } 
    }); 

    ns.ListView = Backbone.View.extend({ 
     initialize: function(collection) { 
      this.el = collection.el; 
      this.collection = collection; 

      this.collection.bind("add", this.addOne, this); 
      _.bindAll(this, "addOne"); 

      this.el.sortable({ 
       axis: "y", 
       connectWith: ".tasks", 
       receive: _.bind(function(event, ui) { 
        // do something here? 
       }, this), 
       remove: _.bind(function(event, ui) { 
        // do something here? 
       }, this), 
       update: _.bind(function(event, ui) { 
        var list = ui.item.context.parentNode; 
        this.collection.setOrder(); 
       }, this) 
      }); 
     }, 
     insert: function(item) { 
      var prefix = this.el.parentsUntil('ul').parent().attr("id"), 
       view = new ns.ContentRow({ 
        model: item, 
        id: prefix + "_" + item.id 
       }); 

      this.el.append(view.render().el); 
     }, 
     addOne: function(item) { 
      if (item.isNew()) { 
       item.save({}, { 
        success: _.bind(function(model, response) { 
         // I should set id from JSON response when live 
         model.set({ id: this.collection.length }); 
         this.insert(model); 
        }, this) 
       }); 
      } else { 
       this.insert(item); 
      } 
     }, 
     addAll: function() { 
      this.collection.each(this.addOne); 
     }, 
     render: function() { 
      this.collection.deferred.done(_.bind(function() { 
       this.addAll(); 
      }, this)); 
     } 
    }); 

    ns.AppView = Backbone.View.extend({ 
     lists: [], 
     initialize: function(holder) { 
      holder.find("ul").each(_.bind(function(index, list) { 
       var Items = new WS.Content(list), 
        App = new WS.ListView(Items); 

       App.render(); 

       this.lists.push(Items); 
      }, this)); 
     } 
    }); 

})(WS); 

$(document).ready(function() { 
    var App = new WS.AppView($("#tasks")); 
}); 

Respuesta

1

Sólo tiene que utilizar Backbone.CollectionView .. que tiene esta funcionalidad incorporada en salir De la caja.

var listView = new Backbone.CollectionView({ 
    el : $("#list1"), 
    sortable : true, 
    sortableOptions : { 
     connectWith : "#list2" 
    }, 
    collection : new Backbone.Collection 
}); 

var listView = new Backbone.CollectionView({ 
    el: $("#list2"), 
    sortable : true, 
    sortableOptions : { 
     connectWith : "#list1" 
    }, 
    collection : new Backbone.Collection 
}); 
+0

Muy bienvenida nueva funcionalidad, gracias! –

2

Estás en el camino correcto. Es probable que desee agregar el ID de cada elemento ordenable en la plantilla en alguna parte. Luego, cuando reciba el evento, sabrá qué modelo agregar o eliminar de la colección. Por ejemplo añadir ...

<div data-id={{id}}> ... my thing ... </div> 

Y en la llamada sortable obtener atributo id del objetivo y llamar Collection.add() o eliminar()

Cuestiones relacionadas