【问题标题】:Backbone View event firing only once after view is rendered渲染视图后仅触发一次主干视图事件
【发布时间】:2013-08-31 20:25:05
【问题描述】:

在路由器中,我使用以下代码创建了一个搜索视图:
if 是只创建一个尚不存在的 new 视图,因为视图永远不会改变。)

search: function () {
    if (!this.searchView) {
        this.searchView = new SearchView();
    }
    $('#content').html(this.searchView.el);
    this.headerView.selectMenuItem('search-menu');
},

在视图中,我有一个事件哈希,将点击事件绑定到搜索按钮:

events: {
    "click .search-query": "search"
},

这会导致事件仅在第一次使用搜索按钮时触发
从搜索功能中删除if 即可解决问题。

但这似乎不是解决此问题的正确方法,因为不需要重新创建视图(重新初始化重新渲染)。

尝试修复:

我尝试如下将this.delegateEvents();添加到搜索视图的渲染函数中(同时将if留在搜索函数中),但没有解决问题:

render:function () {
    console.log('rendering search...');
    $(this.el).html(this.template());
    this.delegateEvents();
    return this;
},


任何建议将不胜感激。

【问题讨论】:

标签: javascript jquery backbone.js


【解决方案1】:

由于您不再调用render(),因此不会再次调用delegateEvents。您可以直接在路由器中拨打delegateEvents。这只是一个例子;可能有更优雅的方法来做到这一点。

delegateEvents 基本上将事件重新绑定到您的视图。如果您的视图的 html 从 dom 中删除,这将很有用。这看起来像您的示例中正在发生的事情。

search: function () {
    if (!this.searchView) {
        this.searchView = new SearchView();
    }
    $('#content').html(this.searchView.el);
    this.searchView.delegateEvents();
    this.headerView.selectMenuItem('search-menu');
}

【讨论】:

  • .html() 调用故意终止事件(如果您有兴趣,请进一步讨论 over here),IMO 的优雅解决方案是根据需要创建和销毁视图,而不是尝试重用它们。
  • 感谢@Gohn67,解决了它。但是,有时最好删除视图,并在需要时重新创建它们,在这种情况下,我意识到我不需要保留视图。
  • 感谢@muistooshort 指出这一点。对于想重用或重新创建元素的任何人来说,您的链接绝对值得一读。此外,我还发现了以下有用信息:Backbone.js : repopulate or recreate the view?.
  • 另外,这个相关的答案和cmets提供了binding and unbinding events的信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多