3

我对 Backbone View 的理解是,每个需要展示模型数据的 html 元素本身都可以是一个 View。

我希望创建链接到特定 div 的视图以显示模型数据。我的问题是,如果我对 el 使用除“body”之外的任何其他内容,则代码将不起作用。

以下代码不起作用:

http://jsfiddle.net/GhaPF/9/

$(document).ready(function() {

var ToDo = Backbone.Model.extend({
    defaults: { "date": "today",
                "task": ""
            },
    initialize: function() {}
});

var ToDoList = Backbone.Collection.extend({
    model: ToDo
});

var ToDoListView = Backbone.View.extend({
    el: "#view1",
    initialize: function(myTodoList) {
        this.todolist = myTodoList;
        this.todolist.bind('add', this.render, this);
    },
    render: function() {
        text = this.todolist.toJSON();
        string = JSON.stringify(text);
        $(this.el).append(string);
        return this;
    },
    events: {
        "keypress #new-todo":  "createOnEnter"
    },
    createOnEnter: function(e) {
      if (e.keyCode != 13) return;
      if (!$("#new-todo").val()) return;
      this.todolist.add({"task": $("#new-todo").val()});
      $("#new-todo").val('');
    }
});

$("#new-todo").focus();
var todolist = new ToDoList();
var myToDoListView = new ToDoListView(todolist);

}); ​</p>

但是,如果我将 'body' 用于 el,它会按我的意愿工作。

如何将 el 设置为特定的 div ?

4

2 回答 2

7

解决方案 http://jsfiddle.net/r3F8q/

你也可以this.setElement('#body1')在渲染中使用

<div id="view-container">
    <input id="new-todo" placeholder="text">
    <div id="view1"></div>
    <div id="view2"></div>
</div>

​</p>

$(document).ready(function() {

var ToDo = Backbone.Model.extend({
    defaults: { "date": "today",
                "task": ""
            },
    initialize: function() {}
});

var ToDoList = Backbone.Collection.extend({
    model: ToDo
});

var ToDoListView = Backbone.View.extend({
    el: "#view-container",
    initialize: function(myTodoList) {
        this.todolist = myTodoList;
        this.todolist.bind('add', this.render, this);
    },
    render: function() {
        text = this.todolist.toJSON();
        string = JSON.stringify(text);
        this.$el.find('#view1').append(string);
        return this;
    },
    events: {
        "keypress #new-todo":  "createOnEnter"
    },
    createOnEnter: function(e) {
      if (e.keyCode != 13) return;
      if (!$("#new-todo").val()) return;
      this.todolist.add({"task": $("#new-todo").val()});
      $("#new-todo").val('');
    }
});

$("#new-todo").focus();
var todolist = new ToDoList();
var myToDoListView = new ToDoListView(todolist);
});

​</p>

于 2012-09-06T11:04:55.467 回答
1

当您使用“#view1”时

"keypress #new-todo":  "createOnEnter"

未绑定,因为#new-todo 不在“#view1”中。检查API

于 2012-09-06T10:02:33.747 回答