0

我正在尝试检测组件中创建的事件。什么都没发生。

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" />  

这是处理创建事件的正确方法还是有更好的方法?
创建新的待办事项时,我需要列表做出反应。
代码见这里

4

1 回答 1

0

这是一个错误: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将其视为属性而不是方法。

于 2014-10-07T16:44:08.053 回答