我问过a question这里建议我使用 Backbone 事件。它工作得很好,除了我的事件监听器 onFormSubmit()
被调用两次。通常我不会关心,但我有一个可以切换某些状态的函数,并且切换两次会产生问题..我认为我的 View 被渲染了两次(基于SO上的其他答案),但它似乎不是所以。我试图理解这里发生的事情背后的“原因”..这是一些代码(删除了不相关的内容)..
这是我的文章表单 View ,它调用触发表单保存上的事件,并触发一次(正确的预期行为),然后重定向回仪表板。
var PostView = Backbone.View.extend({
el: '#content',
articletemplate: _.template($('#article-template-add').html()),
initialize: function() {
this.render();
},
render: function() {
this.$el.html(this.articletemplate({}));
},
events: {
"click .save": "savePost",
},
savePost: function() {
var mypost = new PostModel();
this.model = mypost;
this.model.save(null, {
success: function(model) {
eventBus.trigger('formSubmitted', {
message: "form submitted"
});
app.navigate("/", false);
},
});
},
});
这是我的 Dashboard view(),在上面的表单提交后被调用。这是 onFormSubmit() 执行两次的地方(console.log() 被打印两次)。
var DashboardView = Backbone.View.extend({
el: '#content',
dashboardtemplate: _.template($('#dashboard-template').html()),
initialize: function() {
this.listenToOnce(eventBus, 'formSubmitted', this.onFormSubmit);
this.render();
},
onFormSubmit: function(datahere) {
console.log("onFormSubmit called"); // *** This gets printed twice
},
render: function() {
$(this.el).empty().html(this.dashboardtemplate(this.model.attributes));
},
});
现在,我开始认为主应用程序路由可能存在一些问题?
var AppRouter = Backbone.Router.extend({
routes: {
"": "dashboard",
"article/add": "addarticle",
},
dashboard: function() {
mydashview = new DashboardView();
},
addarticle: function() {
var articleView = new PostView();
},
});
var eventBus = _.extend({}, Backbone.Events);
var app = new AppRouter();
Backbone.history.start();
编辑
我更新了 savePost() 以包括在 this.model.save() 的回调中调用触发器。我强制它创建一个虚拟模型,而不是从表单中获取它。好消息是我能够在这里重新创建行为:http://jsfiddle.net/okswxngv/如果打开控制台,您可以看到 onFormSubmit 调用
打印两次。
最佳答案
您的问题与 ghost view 相关联。有人称之为僵尸。每次进入根页面时都会创建 DashboardView,但不会删除。
这就是为什么他会存在,即使您将新 View 链接到#content div。
您可以在 DashboardView ->initialize 上放置一个断点,看看它被调用了两次。
为了更好地理解,我更改了您的代码并向 View 添加了一个名称(这是创建它的日期)并打印了该名称。
要了解问题,您必须删除不需要的 view当您创建一个新的时。
关于javascript - ListenOnce() 在backbone.js 事件中运行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35832604/