我正在尝试检测组件中创建的事件。什么都没发生。
can.Component.extend({
// todos-list component
// lists todos
tag: "todos-list",
template: can.view("javascript_view/todos-list"),
scope: {
Todo: Todo,
todos: TodoList.slice(0),
todoCreated: function(context, element) {
// new todo is created
var Todo = this.Todo;
new Todo({
name: can.trim(element.val())
}).save();
element.val("");
}
},
events: {
"{Todo} created": function(Todo, event, newTodo) {
console.log("created");
}
}
});模型是
var Todo = can.Model.extend({
// todo model
// fetches things and so on
findAll: function() {
// get all todos
return $.Deferred().resolve(todos);
},
findOne: function(params) {
// get one todo
return $.Deferred().resolve(todos[(+params.id) - 1]);
},
create: function(attributes) {
// creates new todo
var last = todos[todos.length - 1];
$.extend(attributes, {id: last.id + 1, detail: "", tag: ""});
todos.push(attributes);
return $.Deferred().resolve(attributes);
},
update: function(id, attributes) {
// update one todo
$.extend(todos[id - 1], attributes);
return $.Deferred().resolve();
},
destroy: function() {
// destroy todo
return $.Deferred().resolve();
}
}, {});标记是
<input type="text" name="todo" placeholder="What needs to be done" can-enter="todoCreated" /> 这是正确的处理创建事件的方式,还是有更好的方法?
当新的待办事项创建时,我需要列表来做出反应。
请参阅这里是为了代码
发布于 2014-10-07 16:44:08
这是一个bug:https://github.com/bitovi/canjs/issues/1261
这是因为CanJS将Todo构造函数视为方法,因为Todo是JS函数。
您可以通过在用作作用域的can.Map实例上设置Todo来解决这一问题,如下所示:
http://jsfiddle.net/c3bfy/147/
诀窍是在作用域上创建一个单独的视图模型,其中包含您想要的方法:
TodoListViewModel = can.Map.extend({
todoCreated: function(context, element) { ... }
});并更改范围以返回此视图模型的实例,并将Todo作为属性:
scope: function(){
return new TodoListViewModel({Todo: Todo})
},这迫使Todo被视为属性而不是方法。
https://stackoverflow.com/questions/26226898
复制相似问题