【问题标题】:Backbone.js: Binding event to template buttonBackbone.js:将事件绑定到模板按钮
【发布时间】:2013-07-11 18:52:30
【问题描述】:

我正在使用 Backbone.js 构建一个应用程序,其中显示项目列表和占位符“新”项目。容器是一个包含所有子视图并渲染它们的视图。

我已经搜索了一段时间,但无法让它工作。 问题是模板中的“添加”按钮没有触发事件。我猜这是因为渲染发生在稍后的时间点,所以没有分配事件。阅读其他帖子应该由 Backbone.js 处理,但似乎并非如此。在render() 之后添加一个 jQuery 事件处理程序可以完成这项工作,但我认为这不是解决方案。

下面是视图的相关代码:

template: _.template($("#template-time-new").html()),
events: {
  'click #btn-new-time': 'onButtonNewClick'
},
render: function() {
  this.$el.html(this.template());

  return this;
},

onButtonNewClick: function() {
  return false; // in this case: prevent page reload
}

我的模板(翡翠):

script(type="text/template", id="template-time-new").
<h3>
  <label for="new-time-name" class="muted">Name:</label>
  <input id="new-time-name" type="text">
</h3>
<div class="time-inner">
  <form class="form-horizontal">
    <label for="new-time-start" class="muted">From:</label>
    <input id="new-time-start" type="datetime-local">

    <label for="new-time-end" class="muted">to</label> 
    <input id="new-time-end" type="datetime-local">

    <button class="btn" id="btn-new-time">
      Add
    </button>
  </form>
</div>

编辑:

这是来自父视图的代码:

initialize: function() {
  this.newView = new TimeSpanNewView; // <---- the view that is not really working

  this.render();

  // bind event handlers
  this.collection.on('all', this.render, this);
  // fetch data
  this.collection.fetch();
},

render: function() {
  var self = this;

  self.$el.empty();

  if ( self.collection.length > 0 ) {
    self.collection.each(function(timespan) {
      var subView = new TimeSpanView({ // sub views for the items, everything fine here
        model: timespan
      });

      subView.render()
      self.$el.append(subView.el);
    });
  } else {
    self.$el.text("Nothing found.");
  }

  self.$el.append(self.newView.render().el);

  return self;
}

【问题讨论】:

  • 工作正常:jsfiddle.net/ambiguous/MNJd5 你有什么不同的做法?而&lt;button&gt; 真的应该是&lt;button type="button"&gt;
  • 没什么,这就是我提出这个问题的原因。尝试添加 this.delegateEvents(); [就像作为消失的答案发布的那样],现在它工作得很好。
  • 您使用的是什么版本的 Backbone?
  • 我会要求更多代码。我有类似的问题,所以我想看看你如何在父视图中使用你的视图。
  • v1.0.0,来自网站的当前版本。

标签: javascript templates backbone.js underscore.js backbone-events


【解决方案1】:

删除了之前的评论。 好吧,您必须每次都在父视图的render() 中渲染它。但不要做self.$el.html(""); 尝试self.$el.children().detach()。 并将子视图添加为

self.$el.append(self.newView.render().el);

解释:$el 已经包含您的子视图,您不想完全删除子视图。因此,您需要对此调用 detach() - 它会从页面中删除子视图的 DOM 对象,但不会完全删除它。

【讨论】:

  • 不,我只是渲染这个视图一次。也只插入一次,因为它每次都被清理掉(我认为这是可能的唯一方式)。
  • 更新了我的答案,试试看。正如我从您的代码中看到的那样,这可能正是您的问题。它有效,我用解释更新答案。
  • 不抱歉,已经这样做了。感谢您的提示,我现在将使用这种方式渲染我的所有项目。但遗憾的是没有解决事件处理程序不触发的问题。
  • 我只用了你的帮助,但是事件问题还没有解决。
  • 呃,我搞砸了这些编辑。不是 $el.empty(),而是 $el.children().detach()。
猜你喜欢
  • 1970-01-01
  • 2011-07-13
  • 2013-08-15
  • 2010-12-27
  • 2021-10-09
  • 1970-01-01
  • 2018-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多