Hi,
I’m new to canjs and currently studying the TodoMVC examples. This example uses can.connect,superMap for the can.connection.
I would like to do more work after adding and deleting todo’s to the list. Is it possible to add callbacks to the superMap in order to achieve this?
What is the work that you would like to do? There are many ways to do this kind of thing.
One way is to simply do the work after the promise resolves:
this.todo.save().then(() => {
this.todo = new Todo();
}).then(() => {
// do additional work here
});
This is the most direct solution, but probably isn’t the best way to do it, since you would have to put this anywhere in your code that you are adding or deleting todos (and because unit testing becomes difficult doing it this way).
A better solution is to use the “observable” nature of your todos to do whatever it is you need to do.
You can use can-define
's value
or get
behaviors to derive other properties from the length
of your todos list.
If you need to perform DOM manipulation directly you can use can-component
's connectedCallback
or events
, which have access to the element. In these, you would need to listen to the length of your todos list and perform whatever needs to be done.
Hi Kevin,
I am trying to connect the canjs framework to jQuery.DataTables. Adding and removing todo-items should result in adding and removing rows in DataTable. DataTables take care of the DOM-manipulation.
My approach would be to use the create and destroy events that are added to the can-map when using the superMap or baseMap as can-connect class. How can I hook into these events, or is this not the way to go?
@ell I would use the connectedCallback
for this.
The connectedCallback
has access to the element, so you can use it with jquery and you can use listenTo
to listen for add
and remove
events on the list:
var TodoListVM = can.DefineMap.extend({
todos: Todo.List,
...,
connectedCallback(element) {
this.listenTo(this.todos, "add", (ev, addedTodos, index) => {
...
});
this.listenTo(this.todos, "remove", (ev, removedTodos, index) => {
...
});
return this.stopListening.bind(this);
}
});
Make sure to return this.stopListening.bind(this)
so that the listeners are cleaned up if this component is removed from the page. This will prevent memory leaks.