The supports are: React, Redux and Sequelize.
Basically I want to be able to mark an object as being dirty
when the Redux store gets updated.
function updateCar(carToUpdate, car) {
switch(car[1]) {
case "models":
carToUpdate.models = car[3];
carToUpdate.setDirty();
break;
}
};
Then when someone clicks a save button, I want to only update those models that have their dirty flag set to true
var state = request.body;
state.forEach(function (car) {
if (car && car.isDirty) {
updateCar(car);
}
}
Now I have following model for the car:
module.exports = function (sequelize, DataTypes) {
var Cars = sequelize.define('Cars',
{
name: DataTypes.STRING,
type: DataTypes.INTEGER,
models: DataTypes.INTEGER,
//Next is NOT working, this does not make it non-mapped
isDirty: {
type: DataTypes.BOOLEAN,
scope: false
},
},
{
classMethods: {
associate: function (models) {
// associations can be defined here
}
},
instanceMethods: {
setDirty: function() {
this.isDirty = true;
}
}
});
return Cars;
};
Anyone who has experience with non-mapped fields or something similar?
Found it eventually.
The model of the car should contain a VIRTUAL
property:
module.exports = function (sequelize, DataTypes) {
var Cars = sequelize.define('Cars',
{
name: DataTypes.STRING,
type: DataTypes.INTEGER,
models: DataTypes.INTEGER,
isDirty: {
type: DataTypes.VIRTUAL
},
},
{
classMethods: {
associate: function (models) {
// associations can be defined here
}
}
});
return Cars;
};
Next the flag should be set when updating the values:
function updateCar(carToUpdate, car) {
switch(car[1]) {
case "models":
carToUpdate.models = car[3];
carToUpdate.isDirty = true;
break;
}
};
Then the save method can check the isDirty
flag
var state = request.body;
state.forEach(function (car) {
if (car && car.isDirty) {
console.log(car.name +": "+ car.isDirty);
updateCar(car);
}
}, this);
Last but not least, we reset the isDirty
flag to false so we do not update the same models over and over.
var save = function () {
var state = carStore.getState();
return $.ajax({
url: "/Cars/update",
data: JSON.stringify(state),
method: "POST",
contentType: "application/json"
}).then(function() {
carStore.dispatch({
type: 'resetDirty',
data: null
});
});
};
And the dispatch method for resetting the flag:
function updateReducer(state, action) {
switch (action.type) {
case 'load':
return action.data;
case 'update':
return updateCars(action.carChanges, state);
case 'resetDirty':
return resetDirtyFlags(state);
default:
return action.data;
}
}
function resetDirtyFlags(state) {
var newState = $.extend(true, [], state);
if(state) {
newState.forEach(function(car) {
car.isDirty = false;
}, this);
return newState;
}
return newState;
}