gpt4 book ai didi

Backbone.js 如何将 el 设置为特定的 div id

转载 作者:行者123 更新时间:2023-12-04 02:42:09 25 4
gpt4 key购买 nike

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

我希望创建链接到特定 div 的 View 以显示模型数据。我的问题是,如果我对 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);

});​

但如果我使用 'body' 作为 el,它可以按我的意愿工作。

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

最佳答案

解决方案 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>

$(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);
});

关于Backbone.js 如何将 el 设置为特定的 div id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12296690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com