I am working at the client-side part of a web application, that is responsible for getting answers from users for specific questions and storing and restoring them from the database (or cookies) and I am running into the issue that updating the answers from the db will also trigger saving them again (because the same method answerQuestion
is called).
Here's a simplification of my use-case (coffeescript):
class Questionnaire
constructor: ->
@prefillAnswers()
@listenToInput()
@listenToQuestionChanges()
prefillAnswers: ->
for q in @questionNames
@answerQuestion getAnswer(q)
listenToInput: ->
$('.input').on 'change', (e) =>
$input = $(e.currentTarget)
@answerQuestion $input.data('questionName'), $input.val()
listenToQuestionChanges: ->
@subscribeToEvent 'answeredQuestion', (msg, data) =>
saveAnswer(data.question, data.answer)
getAnswer: (qName) ->
# fetches answer from a database (such as cookies, but is irrelevant)
saveAnswer: (qName, answer) ->
# saves the answer
answerQuestion: (qName, answer) ->
@publishEvent 'answeredQuestion', {question: qName, answer: answer} # This part triggers unnecessary saving, but where is the best place for this?
# Change state of UI and data "model"
# ...
My question is, is there an OOP pattern that discusses this issue and possible solutions? I don't know how to start addressing this, and reading an entire book is not an option right now (I however have it on my todo list).
Perhaps this could be rewritten with a MVC pattern, and I'm moving towards that by starting to read the book JavaScript Web Applications, but can't see right now even with MVC, how my problem is avoided in the best way...