Reputation: 13
I am going through the Mithril tutorial and am having trouble understanding m.withAttr
. The guide has the following line in the view layer:
m("input[type=checkbox]", {onclick: m.withAttr("checked", task.done), checked: task.done()})
I have two questions.
1) I understand that the first half, onclick: m.withAttr("checked", task.done)
means, essentially:
'set task.done, using m.prop, to the value of the "checked" attribute'. But what is the purpose of the second half, checked: task.done()
? It seems like it is simply repeating the first half.
2) As I went through the tutorial, I wanted to add the functionality of persisting my Todos to a persistence layer. I created a save function, so that I could refactor the line that I referenced above into something like:
m("input[type=checkbox]", { onclick: todo.vm.markAsDone.bind(todo.vm, task)})
And in my view-model, I had the function:
vm.markAsDone = function(todo) {
m.withAttr("checked", todo.done), checked: todo.done();
todo.save();
};
But this did not work; I get an Uncaught SyntaxError: Unexpected token :
error. I think the problem is that the event is not being properly bound to the markAsDone
function, so it doesn't understand the "checked"
attribute; but I'm not sure how to fix this problem (if that even is the problem).
Thanks for any help.
Upvotes: 1
Views: 1401
Reputation: 3947
Question 1
The second parameter of the m()
function defines attributes on the HTML element, in this case an <input type=checkbox>
will be decorated. (The exception is the special config field)
checked
determines if the input checkbox is checked, so it is required to display the state of the task. onclick
is the event handler that will modify the state.So the attributes do different things, therefore both of them are needed.
Question 2
Since markAsDone
is passed a todo
model, you don't have to do any m.withAttr
call there. Simply modify the model, and let Mithril redraw the view. The redraw happens automatically if you call markAsDone
through an event like onclick
.
If you want more information about the redraw procedure, I summarized it in a previous SO question.
Edit: markAsDone
will probably look like this:
vm.markAsDone = function(todo) {
todo.done(true);
todo.save();
};
Upvotes: 1