私は、複数のユーザーがリアルタイムでデータベースを編集できるアプリケーションを作成しました。私はsocket-ioを使用して、データベースの変更に合わせてすべてのユーザーのページを最新の状態に保ちます。どのようにして要素のchange()メソッドにデータを渡すことができますか?
すべての入力値が変更をブロードキャストしました。 は、私は、入力の変更イベントに関数をバインド言う:
$(".input-field").change(function(ev) {
codeThatChangesOtherInputValuesOnMyPage1;
codeThatChangesOtherInputValuesOnMyPage2;
codeThatChangesOtherInputValuesOnMyPage3;
codeThatChangesOtherInputValuesOnMyPage4;
codeThatChangesOtherInputValuesOnMyPage5;
codeThatChangesOtherInputValuesOnMyPage6;
codeThatChangesOtherInputValuesOnMyPage7;
codeThatChangesOtherInputValuesOnMyPage8;
var tableColumn = $(ev.target).attr('table-col');
var newFieldValue = $(ev.target).val()
broadcastChange(tableColumn, newFieldValue); // this is pseudo code for a socket-io emit()
});
socket.on('runThisWhenReceivingBroadcastFromServer', function(response) {
// response.data has the input element id of element I should update.
// Get the input field i should update
var theInputField = getInputField(response.data)
$(theInputField).val(getNewInputValue(response.data))
$(theInputField).change();
// I call change because I want all my code in the input's change function to run, except for the last line.
});
私はすでにこの問題を修正しましたが、私はその後、ちょうど変更機能上からすべての私のコードをコピーして自分自身を繰り返し、放送受信中にそれを貼り付けていますbroadcastChange行を省略するだけです。しかし、私はDRY(Do not Repeat Yourself)に従いたいと思っています。
codeThatChangesOtherInputValuesOnMyPage1;コードだけです。そのトンのコード。コードを再構築するにはどうしたらいいですか?
私が最初に考えたのは、このような何か(擬似コード)を行うことでした。
$(".input-field").change(function(ev) {
codeThatChangesOtherInputValuesOnMyPage1;
codeThatChangesOtherInputValuesOnMyPage2;
codeThatChangesOtherInputValuesOnMyPage3;
codeThatChangesOtherInputValuesOnMyPage4;
codeThatChangesOtherInputValuesOnMyPage5;
codeThatChangesOtherInputValuesOnMyPage6;
codeThatChangesOtherInputValuesOnMyPage7;
codeThatChangesOtherInputValuesOnMyPage8;
var tableColumn = $(ev.target).attr('table-col');
var newFieldValue = $(ev.target).val()
if (!ev.data.comingFromBroadcastReceiverFunction) {
broadcastChange(tableColumn, newFieldValue); // this is pseudo code for a socket-io emit()
}
});
をしかし、あなたは()を変更するためにデータを渡すことはできません。関数をバインドするときだけです。 関数型プログラミングのアプローチは何ですか?