Im trying to clear data from a Backbone model. Check out the jsfiddle here. Th JS is:
$(function(){
//Define Model
var loginData = Backbone.Model.extend({
defaults: {
token: null,
data: []
},
initialize: function () {
},
/*
* Push name/value to data array. If name is already present, overwrite value. Otherwise, push to end of data array
*/
addToData: function (nameValue) {
var data = this.get('data');
var item, exists = false, index;
for (var key in data) {
// The key is key
item = data[key];
if (item['name'] === nameValue.name) {
exists = true;
index = key;
}
}
if (exists) {
//overwrite value if name already in array
data[index].value = nameValue.value;
} else {
//add to end of array if name not in array
data.push(nameValue);
}
},
clearSensitiveData: function () {
console.log('in clearSensitiveData');
this.set('data', [], { silent: true });
this.set('token', null, { silent: true });
},
});
//Model View & event action
var View = Backbone.View.extend({
initialize: function() {
this.model = new loginData();
},
addData: function(nameValue) {
this.model.addToData(nameValue);
},
clear: function() {
this.model.destroy();
}
});
var view = new View;
view.addData({'username':'abcd'});
console.log('username of view is ');
console.log(view.model.get('data')[0].username);
view.model.clearSensitiveData();
var view2 = new View;
console.log('username of view2 is (this should fail because model should be cleared) ');
console.log(view2.model.get('data')[0].username);
}());
If you look at the console.log outputs, you see:
username of view is (index):100
abcd (index):101
in clearSensitiveData (index):74
username of view2 is (this should fail because model should be cleared) (index):107
abcd
This is very odd as clearSensitiveData() should reset the "data" array attribute, but somehow, the model remains populated...