ahe*_*ick 28 jquery backbone.js
我正在尝试使用Backbone JS,到目前为止,一切似乎都很有意义并且工作顺利.
但是,使用下面的代码,我的自定义事件似乎没有被触发.以下代码中的任何内容都可以说明原因可能是什么?我是否需要在视图中"初始化"任何内容?关于代码/结构的任何其他指针也会很酷.下面是我的完整JS/HTML.
JS
var Todo = Backbone.Model.extend({});
var TodoCollection = Backbone.Collection.extend({
model: Todo,
url: '/Home/Todos'
});
var AppView = Backbone.View.extend({
// where it should listen, required?
el: $(".content"),
events: {
"keypress #new-todo": "enter"
},
initialize: function () {
// _.bindAll(this, "render", "createOnEnter");
// this.collection.bind("all", this.render);
},
hi: function () {
alert('ohai');
},
render: function () {
var lis = '';
$.each(this.collection.models, function () {
lis += '<li>' + this.get('Text') + '</li>';
});
$('#todo-list').append(lis);
return this.el;
},
enter: function (e) {
alert('hi');
}
});
var TodoController = Backbone.Controller.extend({
routes: {
"": "todos"
},
initialize: function (options) { },
todos: function () {
var todolist = new TodoCollection();
todolist.fetch({
success: function (data) {
var appview = new AppView({ collection: data });
appview.render();
}
});
}
});
$(function () {
window.app = new TodoController();
Backbone.history.start();
});
Run Code Online (Sandbox Code Playgroud)
HTML
<div id="todoapp">
<div class="content">
<input id="new-todo" placeholder="What needs to be done?" type="text" />
<div id="todos">
<ul id="todo-list">
</ul>
</div>
<a href="#">say hey</a>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
Jul*_*ien 37
el: $(".content")
Run Code Online (Sandbox Code Playgroud)
试试这个:
var appview = new AppView({ el:$(".content"), collection: data });
Run Code Online (Sandbox Code Playgroud)
你不能在那里调用jQuery,因为尚未创建DOM.当视图作为我的示例或初始化加载时,您必须这样做.
Jes*_*obs 16
此外,要使您的事件起作用,您必须将渲染功能中的内容绑定到this.el. 事件都绑定到您指定的元素,因此您需要将事件生成元素作为子元素绑定到充当委托者的元素.
| 归档时间: |
|
| 查看次数: |
20098 次 |
| 最近记录: |