我对javascript和骨干相对较新。我正在攻击一个简单的,初学者级的骨干应用程序。我有两种观点:Home和NewEntry。在Home,我点击“新条目”来渲染NewEntry。从NewEntry,我点击“取消”来渲染Home。所以,我想分别点击“取消”和“新条目”在Home和NewEntry之间切换。
然而,它不起作用。这就是我尝试做的事情:
我非常难过!我无法弄清楚为什么。我想知道一个不同的事件是否会被解雇,但我不知道如何。有人知道我应该怎么做吗?
JavaScript的:
var Views = {
Home: Backbone.View.extend({
template: $('#homeview-template').template(),
initialize: function() {
this.entries = new Collections.Entries();
this.entries.on('all', this.render, this);
this.entries.fetch();
},
render: function() {
var currDate = getCurrentDate();
var innerHtml = $.tmpl(this.template, {
currDate: currDate
});
this.$el.html(innerHtml);
return this;
}
}),
NewEntry: Backbone.View.extend({
template: $('#newentryview-template').template(),
events: {
'click button#cancel-new-entry': 'cancelNewEntry',
'all': 'logEvents'
},
initialize: function() {
// currently, do nothing
},
render: function() {
var innerHtml = $.tmpl(this.template);
this.$el.html(innerHtml)
return this;
},
cancelNewEntry: function() {
console.log("test 1");
window.router.showHome();
},
logEvents: function(evnt) {
console.log("works");
console.log("event", evnt);
}
})
};
var Router = Backbone.Router.extend({
initialize: function(inputs) {
this.homeView = new Views.Home();
this.newEntryView = new Views.NewEntry();
this.el = inputs.el
},
routes: {
"": 'showHome',
"#": 'showHome',
'new': 'writeNewEntry'
},
showHome: function() {
this.el.empty();
this.navigate("");
this.el.append(this.homeView.render().el);
},
writeNewEntry: function() {
this.el.empty();
this.navigate('new');
this.el.append(this.newEntryView.render().el);
}
});
HTML:
<script id='homeview-template' type='text/template'>
<h1 class='title'>My Journal</h1>
<div id='curr-date-new-entry'>
<div id='curr-date'>${currDate}</div>
<div id='new-entry'>
<a href='#/new'>New Entry</a>
</div>
</div>
</script>
<script id='newentryview-template' type='text/template'>
<h1 class='title'>New Entry</h1>
<input id='new-entry-title' placeholder='New entry title' type='text'/>
<input id='new-entry-body' placeholder='New entry content' type='text'/>
<button id='submit-new-entry'>Submit</button>
<button id='cancel-new-entry'>Cancel</button>
</script>
答案 0 :(得分:0)
这可能解决了您的问题:
writeNewEntry: function() {
this.el.empty();
this.navigate('new');
this.el.append(this.newEntryView.render().el);
//fix: http://backbonejs.org/#View-delegateEvents
this.newEntryView.delegateEvents();
}
但是如果您不重用视图,我建议您直接在方法writeNewEntry上实例化视图而不是初始化,这样您就不需要手动调用delegateEvents:
writeNewEntry: function() {
this.el.empty();
this.navigate('new');
this.newEntryView = new Views.NewEntry();
this.el.append(this.newEntryView.render().el);
}