todo_list: Fix list item indexing in race condition.

The todo_widget was using the using a counter to store the key value of
every task. This would cause assiging multiple tasks the same key value
in a race condition. To avoid this we make "sender_id" a part of the key
along with the counter.

Also the `key` now not being a integer value, we can't use it to find the
index of the task using it. Thus, a function is made that will find the
index of task whose key is sent by the user to strike.
This commit is contained in:
majordwarf
2020-03-14 19:57:56 +05:30
committed by showell
parent b8ef841867
commit 8ea3bfb927
2 changed files with 12 additions and 6 deletions

View File

@@ -7,7 +7,7 @@ exports.task_data_holder = function () {
const all_tasks = [];
const pending_tasks = [];
const completed_tasks = [];
let my_idx = 0;
let my_idx = 1;
self.get_widget_data = function () {
@@ -24,6 +24,10 @@ exports.task_data_holder = function () {
const task_exists = all_tasks.some(item => item.task === task);
return task_exists;
},
get_task_index: function (list, val) {
return Object.keys(list).find(index => list[index].key === val);
},
};
self.handle = {
@@ -46,6 +50,7 @@ exports.task_data_holder = function () {
inbound: function (sender_id, data) {
const idx = data.key;
const key = idx + "," + sender_id;
const task = data.task;
const desc = data.desc;
const completed = data.completed;
@@ -54,7 +59,7 @@ exports.task_data_holder = function () {
task: task,
desc: desc,
user_id: sender_id,
key: idx,
key: key,
completed: completed,
};
@@ -81,7 +86,8 @@ exports.task_data_holder = function () {
inbound: function (sender_id, data) {
const key = data.key;
const task = all_tasks[key];
const task_index = self.check_task.get_task_index(all_tasks, key);
const task = all_tasks[task_index];
let index;
if (task === undefined) {
@@ -89,7 +95,7 @@ exports.task_data_holder = function () {
return;
}
all_tasks[key].completed = !all_tasks[key].completed;
all_tasks[task_index].completed = !all_tasks[task_index].completed;
// toggle
if (task.completed) {

View File

@@ -3,7 +3,7 @@
<li>
<button class="task" data-key="{{ key }}">
</button>
<span class="task">{{ key }}. <strong>{{ task }}</strong>{{#if desc }} - {{ desc }}{{/if}}</span>
<span class="task"><strong>{{ task }}</strong>{{#if desc }} - {{ desc }}{{/if}}</span>
</li>
{{/each}}
{{#each completed_tasks}}
@@ -11,6 +11,6 @@
<button class="task-completed task" data-key="{{ key }}">
<img class="task-completed" src="/static/images/checkbox-green.svg" data-key="{{ key }}"/>
</button>
<span class="task">{{ key }}. <strike><em><strong>{{ task }}</strong>{{#if desc }} - {{ desc }}{{/if}}</em></strike></span>
<span class="task"><strike><em><strong>{{ task }}</strong>{{#if desc }} - {{ desc }}{{/if}}</em></strike></span>
</li>
{{/each}}