简体   繁体   English

Backbone.js:在视图内调用自定义事件?

[英]Backbone.js: calling custom events inside a View?

I would like to update part of my view when the user types into a input field. 当用户在输入字段中键入内容时,我想更新部分视图。 Initially I bound to the keyup event listener within the View's events field, and that worked well: 最初,我在View的events字段中绑定了keyup事件侦听器,并且效果很好:

window.AppView = Backbone.View.extend({
 el: $("#myapp"),
 events: {
   "keyup #myInput": "updateSpan",
 }, ...
 updateSpan: function() { 
     this.span.text(this.input.val());
 }, ...
});

But then I realised that keyup updated too often and made the app slow. 但是后来我意识到, keyup更新太频繁了,使应用程序变慢了。 So I decided to use the typeWatch plugin so the event would only fire the user stopped typing. 因此,我决定使用typeWatch插件,以便该事件仅会触发用户停止键入。 But now I don't know how to set the custom event listener in Backbone. 但是现在我不知道如何在Backbone中设置自定义事件侦听器。 Currently I have this: 目前我有这个:

window.AppView = Backbone.View.extend({
 initialize: { 
  var options = {
      callback: function(){ 
        alert('event fired'); 
        this.updateSpan; 
      },
      wait:750
  }
  this.input.typeWatch(options);
 }, ...
 updateSpan: function() { 
     this.span.text(this.input.val());
 }, ...
});

Two questions: 两个问题:

  1. I see the alert, but updateSpan is not being fired. 我看到了警报,但未updateSpan I think I'm using this incorrectly in the callback, but how should I do it? 我认为我使用this回调不正确,但我应该怎么办呢?
  2. Is initialize now the right place to set the typeWatch event listener, or can I continue to use the events field as I did before? 现在initialize是设置typeWatch事件侦听initialize的正确位置,还是可以像以前一样继续使用events字段?

You aren't actually calling updateSpan , and you're right that this wont be the correct thing. 您实际上并不是在调用updateSpan ,并且您说对了, this是正确的。 Easiest way to solve it is to just capture the view into another variable first: 解决问题的最简单方法是先将视图捕获到另一个变量中:

  var v = this;
  var options = {
    callback: function() {
      alert('event fired');
      v.updateSpan();
    },
    wait: 750
  };
  this.input.typeWatch(options);

As for your second question, usually I will attach functionality like this in initialize if it's on the base element and in render if it's not, so I think in this case you've probably got it right. 至于第二个问题,通常我会在initialize如果它位于基本元素上)和render如果不在此元素中)中附加这样的功能,因此我认为在这种情况下,您可能正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM