2013-06-20 16 views
11

Ho un'applicazione di base che utilizza Backbone.js che non effettua chiamate PUT (aggiornamento del modello). Dal front-end, che chiamo una funzione dei modelli save non effettua una chiamata PUT; tuttavia, se lo sostituisco con destroy, effettua una chiamata DELETE al back-end. Qualcuno ha idea di quale potrebbe essere il problema? La funzione che non sta eseguendo una richiesta PUT è la funzione saveTask.Backbone.js - model.save() non attiva una richiesta PUT

App.Views.Task = Backbone.View.extend({ 
    template: _.template("<label>ID:</label><input type='text' id='taskId' name='id' value='<%= _id %>' disabled /><br><label>Title:</label><input type='text' id='title' name='title' value='<%= title %>' required/><br><label>Content:</label><input type='text' id='content' name='content' value='<%= content %>'/><br><button class='save'>Save</button>"), 
    events: { 
     "change input":"change", 
     "click .save":"saveTask" 
    }, 
    render: function(eventName){ 
     $(this.el).html(this.template(this.model.toJSON())); 
     //console.log(this.generateTemplate()); 
     return this; 
    }, 
    change: function(event){ 
     var target = event.target; 
     console.log('changing ' + target.id + ' from: ' + target.defaultValue + ' to: ' + target.value); 
     change[target.name] = target.value; 
     this.model.set(change);*/ 
    }, 
    saveTask: function(){ 
     this.model.set({ 
      title:$("#title").val(), 
      content:$("#content").val() 
     }); 
     if(this.model.isNew()){ 
      App.taskList.create(this.model); 
     } else { 
      this.model.save({}); 
     } 
    } 
}); 
+0

Quale versione di Backbone stai usando? Ho avuto alcuni problemi durante l'aggiornamento di un modello con la versione 0.9.9. Potrebbe essere un errore silenzioso durante il salvataggio o un bug con la tua versione di backbone. – mor

risposta

18

Se il modello è nuovo, al momento del salvataggio verrà generato un metodo di post. Se la tua modella tuttavia non è nuova e la stai aggiornando, sparerà un PUT.

se questo non funziona per te potrebbe essere perché il tuo modello non ha una proprietà id, nel caso tu stia usando un id con un nome diverso, ad esempio taskID, quindi nel tuo modello devi impostare idAttribute a taskID in modo che backbone utilizzi questa proprietà come ID e tutto sarà normale.

come questo:

var Task= Backbone.Model.extend({ 
    idAttribute: "taskId" 
}); 

ecco il link alla documentazione sul Idattibute http://backbonejs.org/#Model-idAttribute

anche un altro problema potrebbe essere il {} nel vostro salvare chiamano provare solo

this.model.save(); 

anziché

this.model.save({}); 
+0

Grazie per la risposta. Il mio modello ha una proprietà ID, e ho impostato 'idAttribute' - per essere sicuro, ho controllato l'id del modello (' this.model.id') mentre provo a salvare. Tuttavia, non si attiva ancora un PUT e 'model.destroy()' funziona bene.Mi manca qualcos'altro? –

+0

perché hai il {} all'interno della chiamata di salvataggio? penso che dovrebbe essere solo model.save(); senza alcun oggetto vuoto letterale come parametro. –

+0

Grazie - è un errore di battitura (precedentemente provato a utilizzare la callback di successo), ma non sembra essere correlato (nessuna differenza). Il modello sta cambiando correttamente (gli attributi sono aggiornati), ma non il salvataggio sul server. –

2

Credo modello è sempre opzioni aspetta parametri e probabilmente anche i callback

this.model.save(null, { 
    success: function (model, response) { 

     // 
    }, 
    error: function() { 
     // 
    } 
}); 

Se si guarda a Backbone src, si noterà che anche ...

======

// Set a hash of model attributes, and sync the model to the server. 
// If the server returns an attributes hash that differs, the model's 
// state will be `set` again. 
save: function (key, val, options) { 
    var attrs, method, xhr, attributes = this.attributes; 

    // Handle both `"key", value` and `{key: value}` -style arguments. 
    if (key == null || typeof key === 'object') { 
     attrs = key; 
     options = val; 
    } else { 
     (attrs = {})[key] = val; 
    } 

    options = _.extend({ 
     validate: true 
    }, options); 

    // If we're not waiting and attributes exist, save acts as 
    // `set(attr).save(null, opts)` with validation. Otherwise, check if 
    // the model will be valid when the attributes, if any, are set. 
    if (attrs && !options.wait) { 
     if (!this.set(attrs, options)) return false; 
    } else { 
     if (!this._validate(attrs, options)) return false; 
    } 

    // Set temporary attributes if `{wait: true}`. 
    if (attrs && options.wait) { 
     this.attributes = _.extend({}, attributes, attrs); 
    } 

    // After a successful server-side save, the client is (optionally) 
    // updated with the server-side state. 
    if (options.parse === void 0) options.parse = true; 
    var model = this; 
    var success = options.success; 
    options.success = function (resp) { 
     // Ensure attributes are restored during synchronous saves. 
     model.attributes = attributes; 
     var serverAttrs = model.parse(resp, options); 
     if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs); 
     if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) { 
      return false; 
     } 
     if (success) success(model, resp, options); 
     model.trigger('sync', model, resp, options); 
    }; 
    wrapError(this, options); 

    method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); 
    if (method === 'patch') options.attrs = attrs; 
    xhr = this.sync(method, this, options); 

    // Restore attributes. 
    if (attrs && options.wait) this.attributes = attributes; 

    return xhr; 
}, 
2

Nel mio caso si fallisce a causa di validations.As risparmio il modello di convalida tutti gli attributi del modello e la collezione che sto usando l'interfaccia della messa in vendita non richiede tutto il un ttributes del modello.

Mi trovavo ad affrontare gli stessi problemi e ho cercato su Google e ho trovato la tua domanda e letto la soluzione e i commenti. Mi rendo conto che in specifiche backbone aggiornate si dice che quando model.save() viene eseguito prima delle richieste del modello, prima call validate e se la convalida ha esito positivo rispetto a quello che andrà avanti, altri saggi falliscono, e questo è il motivo per cui non mostra alcuna richiesta di rete nella scheda di rete del debugger di Chrome.

Ho scritto la soluzione per il caso che sto affrontando, altri potrebbero affrontare diversi problemi.

0

Il backbone è ciò che ho utilizzato. Devi passare in 'aggiornamento' come primo parametro (il parametro 'metodo').

+0

Sarebbe bello sapere a cosa serve il voto negativo. Molto più costruttivo per me e anche questo sito :) – Stubbs

Problemi correlati