2016-05-13 113 views
0

的支撐件:反應,終極版和Sequelize。 基本上,我希望能夠在Redux商店更新時將對象標記爲dirty非映射屬性 - Sequelize

function updateCar(carToUpdate, car) { 
    switch(car[1]) { 
     case "models": 
      carToUpdate.models = car[3]; 
      carToUpdate.setDirty(); 
      break; 
    }  
}; 

然後當有人點擊保存按鈕,我想只更新那些有自己的髒標誌設置爲true

var state = request.body; 

state.forEach(function (car) { 
    if (car && car.isDirty) { 
     updateCar(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; 
}; 

任何人誰擁有非映射字段或類似的東西的經歷?

回答

1

找到它最終。

汽車的模型應該包含VIRTUAL屬性:

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; 
}; 

接下來的標誌應該更新值時設置:

function updateCar(carToUpdate, car) { 
    switch(car[1]) { 
     case "models": 
      carToUpdate.models = car[3]; 
      carToUpdate.isDirty = true; 
      break; 
    }  
}; 

然後保存方法可以檢查isDirty標誌 var state = request.body;

state.forEach(function (car) { 
    if (car && car.isDirty) { 
     console.log(car.name +": "+ car.isDirty); 
     updateCar(car); 
    } 
}, this); 

最後但並非最不重要的,我們將重置isDirty標誌設置爲false,所以我們不一遍又一遍更新同一型號。

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 
     }); 
    }); 
}; 

而對於重新設置標誌的調度方法:

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; 
} 
+0

你應該接受你自己的答案:) –