首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >backbone.js todomvc向模型添加更多属性

backbone.js todomvc向模型添加更多属性
EN

Stack Overflow用户
提问于 2013-04-21 04:53:43
回答 1查看 1.1K关注 0票数 0

我想尝试一下Backbone.js,并从著名的TodoMVC-App开始。我想通过输入字段添加更多的属性(或者通常只有一个输入字段带有"todo"),但是我不知道怎么做。

在我尝试Angular.js之前,这要简单一点--现在我被困在如何为每个输入域添加更多属性的问题上。

谁能给我一个提示,实现这一点的最好/最简单的方法是什么?

一些相关的代码片段:

Index.html:

代码语言:javascript
复制
    <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

代码语言:javascript
复制
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:

代码语言:javascript
复制
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('');
}

希望这是足够的信息,否则请告诉我!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-21 05:42:54

遵循标题所做的方式。

添加新输入。更改appView#newAttributes方法以将新输入的值传递给模型。

更改appView#createOnEnter方法以重置该字段。

更改#item-template,以便在Todo模板中包含新属性。

其他一切都将是自动的(包括将新属性设置为模型(作为参数传递)和将新属性传递给模板(因为我们使用Model#toJSON方法))。

编辑:

this.$input是对this.$('#new-todo')的引用(请参阅initialize方法),因此它的val是标题。您需要创建一个新的var:

initialize

代码语言:javascript
复制
this.$quantity = this.$('#newQuantity');

newAttributes

代码语言:javascript
复制
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

代码语言:javascript
复制
this.$quantity.val('');
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16125079

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档