【发布时间】:2013-12-07 13:02:20
【问题描述】:
我目前正忙于编写我的第一个 Backbone、RequireJS 和 jQuery 移动应用程序,但我在事件监听器方面遇到了一些问题,它们不会触发。 我知道这是一个常见问题,但我找不到正确的解决方案。
这是我的代码:
index.html 正文
<body>
<div data-role="page" id="loading"></div>
</body>
路由器
define([
'jquery',
'backbone',
'views/projects/ProjectsView',
'views/projects/AddProjectView'
], function($, Backbone, ProjectsView, AddProjectView) {
return Backbone.Router.extend({
initialize: function() {
$(document).on('click', '[data-rel="back"]', function(event) {
window.history.back();
return false;
});
},
routes: {
'addProject': "addProject",
'*actions': 'showProjects' // Default
},
addProject: function () {
new AddProjectView().navigate();
}
showProjects: function() {
new ProjectsView().navigate();
}
});
});
AddProjectView(有事件的问题页面)
define([
'jquery',
'underscore',
'backbone',
'models/ProjectModel',
'collections/ProjectsCollection',
'text!/templates/projects/editProjectTemplate.html'
], function($, _, Backbone, ProjectModel, ProjectsCollection, editProjectTemplate){
var EditProjectView = Backbone.View.extend({
el: '#editProject',
events: {
"form submit": "addProject"
},
addProject: function(e){
e.preventDefault();
var form = $(this.el).find('form');
var project = new ProjectModel({ title: form.find('input[name=title]').val(), description: form.find('input[name=description]').val() });
var projectsCollection = new ProjectsCollection();
projectsCollection.fetch();
projectsCollection.add(project);
project.save();
window.location = '#project';
return false;
},
render: function(){
this.template = _.template(editProjectTemplate, { type: 'toevoegen', action: 'toevoegen' });
this.$el.html(this.template);
return this;
},
navigate: function() {
var page = this.render();
$('body').append(page.template);
$.mobile.changePage( '#editProject' , { changeHash: false } );
}
});
return EditProjectView;
});
编辑项目模板
<div data-role="page" id="editProject">
<div data-role="header" data-position="fixed" data-tap-toggle="false">
<a href="#projects" data-transition="slide" data-direction="reverse" class="ui-btn ui-btn-left ui-nodisc-icon ui-corner-all ui-btn-icon-notext ui-icon-carat-l">Back</a>
<h1>Project <%= type %></h1>
</div>
<div role="main" class="ui-content">
<form id="addProjectForm">
<ul data-role="listview" data-inset="true">
<li data-role="fieldcontain">
<label for="title">Titel</label>
<input type="text" name="title" id="title" value="" />
</li>
<li data-role="fieldcontain">
<label for="description">Omschrijving</label>
<textarea cols="40" rows="10" name="description" id="description"></textarea>
</li>
<li data-role="fieldcontain">
<input type="submit" value="Project <%= action %>" />
</li>
</ul>
</form>
</div>
</div>
我尝试将 el 设置为“body”,然后使事件正常工作,但是当我第二次使用它时,addProject 事件被触发了两次。而当我第三次提交表单时,addProject 事件被触发了 3 次。
感谢您的帮助!
【问题讨论】:
-
这个问题显示了研究工作;它有用且清晰。也许,为了研究控制台输出,一个工作示例(例如 jsFiddle 或 jsBin)会受到赞赏。
标签: jquery jquery-mobile backbone.js