简体   繁体   中英

Mithril.js m.withAttr: Passing event to another function

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM