2011-12-22 9 views
8

Estoy tratando de obtener backbone.js para cargar json. El json carga, pero no estoy seguro de cómo conseguir los elementos en mi colección. O tal vez eso sucede automáticamente y simplemente no puedo rastrear. ¿problema de alcance?cómo agregar json a la red troncal, colección js usando fetch

// JS código

//model 
var Client = Backbone.Model.extend({ 
    defaults: { 
     name: 'nike', 
     img: "http://www.rcolepeterson.com/cole.jpg" 
    }, 
}); 
//collection 
var ClientCollection = Backbone.Collection.extend({ 
    defaults: { 
     model: Client 
    }, 
    model: Client, 
    url: 'json/client.json' 
}); 
//view 
var theView = Backbone.View.extend({ 
    initialize: function() { 
     this.collection = new ClientCollection(); 
     this.collection.bind("reset", this.render, this); 
     this.collection.bind("change", this.render, this); 
     this.collection.fetch(); 
    }, 
    render: function() { 
     alert("test" + this.collection.toJSON()); 
    } 
}); 
var myView = new theView(); 

// JSON

{ 
    "items": [ 
     { 
      "name": "WTBS", 
      "img": "no image" 
     }, 

     { 
      "name": "XYC", 
      "img": "no image" 
     } 
    ] 
} 

Respuesta

16

Su JSON no está en el formato correcto, se puede fijar el JSON o añadir un toque a la columna vertebral en el método de análisis:

var ClientCollection = Backbone.Collection.extend({ 
    defaults: { 
     model: Client 
    }, 
    model: Client, 
    url: 'json/client.json', 

    parse: function(response){ 
     return response.items; 
    } 
}); 

O arreglar su JSON:

[ 
     { 
      "name": "WTBS", 
      "img": "no image" 
     }, 

     { 
      "name": "XYC", 
      "img": "no image" 
     } 
    ] 
+0

Todavía no puede conseguir que funcione. si mantengo el json el mismo y agrego el análisis: function (response, xhr) { alert ("Collection: ClientList: parse:" + response.items.length) recibo una alerta. intenté cambiar el json y no recibí alertas en la colección o ver return response.items; } veo una alerta. No recibo ninguna alerta en mi función de renderizado en mi opinión –

+0

@ColePeterson puedes hacer un jsfiddle – Esailija

+0

No estaba seguro de cómo configurar esto es jsfiddle, lo siento, mi ejemplo está incompleto. pero aquí está en jsfiddle [link] (http://jsfiddle.net/cole/bQHsb/) cualquier ayuda sería increíble. de nuevo, el análisis funciona pero el render en la vista nunca se dispara. –

0

Si utiliza API REST, intente apagar estos parámetros:

Backbone.emulateHTTP Backbone.emulateJSON

Cuestiones relacionadas