2014-10-07 73 views
0

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

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

是处理创建的事件的这种正确的做法还是有更好的办法?
我需要列表来反应,当新的待办事项创建。
参见here for code

+0

'todos'数组来自哪里? – 2014-10-07 03:16:24

+0

你渲染一个包含''元素的模板吗?你是否在页面中插入了该模板的结果? – 2014-10-07 03:17:59

+0

todos有一个var TodoList = new Todo.List({})的实例,是的,我正在渲染包含待办事项列表的模板 – 2014-10-07 11:21:51

回答

0

这是一个错误:https://github.com/bitovi/canjs/issues/1261

这是由于CanJS处理Todo构造成方法,因为Todo是一个JS函数。

可以解决这个问题通过直接用作范围can.Map例如设置待办事项如下所示:

http://jsfiddle.net/c3bfy/147/

关键是要创造你想要的方式单独视图模型在范围:

TodoListViewModel = can.Map.extend({ 
    todoCreated: function(context, element) { ... } 
}); 

而要改变你的范围与Todo返回此视图模型的实例作为一个属性:

scope: function(){ 
    return new TodoListViewModel({Todo: Todo}) 
}, 

这会迫使Todo被视为属性而不是方法。