我想尝试一下Backbone.js,并从著名的TodoMVC-App开始。我想通过输入字段添加更多的属性(或者通常只有一个输入字段带有"todo"),但是我不知道怎么做。
在我尝试Angular.js之前,这要简单一点--现在我被困在如何为每个输入域添加更多属性的问题上。
谁能给我一个提示,实现这一点的最好/最简单的方法是什么?
一些相关的代码片段:
Index.html:
<tr class="userInputs" >
<td><input id="toggle-all" type="checkbox"></td>
<td><input type="text" id="new-todo" placeholder="What needs to be done?" autofocus style="width: 150px"/></td>
<td><input type="text" id="newQuantity"/></td>
<td colspan="2"><a ><img src="img/plus.png" id="addItem"></a></td>
</tr>model/todo.js
app.Todo = Backbone.Model.extend({
// Default attributes for the todo
// and ensure that each todo created has `title` and `completed` keys.
defaults: {
title: '',
quantity: 0,
completed: false
}
});views/app.js:
initialize: function() {
this.allCheckbox = this.$('#toggle-all')[0];
this.$input = this.$('#new-todo');
this.$footer = this.$('#footer');
this.$main = this.$('#main');
this.listenTo(app.Todos, 'add', this.addOne);
this.listenTo(app.Todos, 'reset', this.addAll);
this.listenTo(app.Todos, 'change:completed', this.filterOne);
this.listenTo(app.Todos, 'filter', this.filterAll);
this.listenTo(app.Todos, 'all', this.render);
app.Todos.fetch();
}
addOne: function( todo ) {
var view = new app.TodoView({ model: todo });
$('#todo-list').append( view.render().el );
}
newAttributes: function() {
return {
title: this.$input.val().trim(),
quantity: this.$input.val().trim(),
order: app.Todos.nextOrder(),
completed: false
};
}
createOnEnter: function(e) {
app.Todos.create( this.newAttributes() );
this.$input.val('');
}希望这是足够的信息,否则请告诉我!
发布于 2013-04-21 05:42:54
遵循标题所做的方式。
添加新输入。更改appView#newAttributes方法以将新输入的值传递给模型。
更改appView#createOnEnter方法以重置该字段。
更改#item-template,以便在Todo模板中包含新属性。
其他一切都将是自动的(包括将新属性设置为模型(作为参数传递)和将新属性传递给模板(因为我们使用Model#toJSON方法))。
编辑:
this.$input是对this.$('#new-todo')的引用(请参阅initialize方法),因此它的val是标题。您需要创建一个新的var:
在initialize中
this.$quantity = this.$('#newQuantity');在newAttributes中
quantity: this.$quantity.val();
// you're not making any check here
// add one if necessary (you can use underscore), eg
// _.isNumber(quantity = this.$('#newQuantity')) ? quantity : 0
// number being declared before, else it'd be global在createOnEnter中
this.$quantity.val('');https://stackoverflow.com/questions/16125079
复制相似问题