我現在正在忙於編寫我的第一個Backbone,RequireJS & jQuery移動應用程序,但是我遇到了一些事件監聽器的問題,他們不會觸發。 我知道這是一個常見問題,但我找不到合適的解決方案。Backbone + 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;
});
EditProjectTemplate
<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爲「體」,然後在工作時很好,但是當我用它第二次addProject事件被擊發兩次。當我第三次提交表單時,addProject事件被激發3次。
感謝您的幫助!
這個問題表明的研究工作;它是有用和清楚的。也許,一個工作的例子,如jsFiddle或jsBin將不勝感激,爲了研究控制檯的輸出。 –