Backbone 事件回调绑定

Backbone event callback bind

我正在尝试将用户定义的回调绑定为 Backbone 的点击事件。

var View = Backbone.View.extend({
    
    events: {
      'click': 'testClick'
    },
    
    tagName: "li",
    
    attributes: {
      class: "item"
    },
    
    initialize: function() {
      
        this.render();
      
    },
    
    testClick: function(){      
      
    },
    
    render: function() {
      
      $("#container").append(this.$el.html("Click Me!!"));
      
    }
    
  });

function Item() {  
  
  var _view = View.extend({
    
    testClick: this.testClick.bind(this)
    
  });
  
  this.view = new _view();
  
}

Item.prototype = {
  
  testClick: function() {
    
    alert("testClick from prototype called!");
    
  }
  
};


var myItem = new Item();

myItem.testClick = function() {
  alert("testClick from instance called!");
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>

</head>
<body>
  <div id="container"></div>
</body>
</html>

点击 "Click me",它会提醒 "testClick from prototype called!"

我不确定为什么没有调用来自实例的警报。我在这里做错了什么?请帮忙!

因为下面一行:

testClick: this.testClick.bind(this)

分离 Item 实例的 testClick 函数成员。您本质上是在重用一个函数,并且这两种方法之间没有联系。

考虑这个例子:

var obj = {
   foo: function() {
      console.log('I was foo!');
   }
}

var detachedFoo = obj.foo;
obj.foo = function() {
   console.log('The new foo!');
}

obj.foo === detachedFoo // false
obj.foo() // logs 'The new foo!'
deatchedFoo(); // logs 'I was foo!'

如果您使用以下语法,alert 将显示 "testClick from instance called!"。

testClick: () => {
   this.testClick();
}

这是因为上面的代码调用了Item实例的当前.testClick方法。