Reputation: 161
I'm new with backbone.js. How can I store data in my localstorage and retrieve them? I am using jeromegn's Backbone.localStorage but why can't I add or save it into the localstorage?
Here's my collection:
var Cases = Backbone.Collection.extend({
localStorage: new Backbone.LocalStorage('dataObject'),
});
Here's my view:
var CreateCase = Backbone.View.extend({
el: '.case',
render: function(){
var template = _.template($('#create-case-view').html(), {});
this.$el.html(template);
},
events: {
'submit #caseForm': 'createCase',
'click .back': 'returnBack',
'focus #c_round': 'datePicker'
},
createCase: function(e){
var caseDetails = $(e.currentTarget).serializeObject();
var cases = new Cases();
//console.log(caseDetails);
cases.add(caseDetails, {
success: function(cases){
console.log(cases); //I CAN'T ADD/SAVE IT TO THE COLLECTION
//router.navigate('', {trigger: true});
}
});
return false;
}
});
When user submits the form it should be added to the collection.
How can I retrieve it from the collection? I used cases.fetch(); but there's no data.
Upvotes: 0
Views: 1520
Reputation: 2856
I'm not aware of any version of Backbone which accepts a success
callback for the Collection.add function. Based on your code, it looks like you want the Collection.create function instead, which will not only add your model, but also save it (i.e. perform the sync).
var Cases = Backbone.Collection.extend({
localStorage: new Backbone.LocalStorage('dataObject'),
});
var cases = new Cases();
cases.create({caseNo: 1, caseName: 'another case'}, {
success: function(caseModel){ // note, this is the model
console.log(caseModel);
}
});
See it in action here: https://jsfiddle.net/vbj2ouey/1/ (due to sandboxing it only worked in JSFiddle)
Upvotes: 3