Backbone事件回调绑定

时间:2016-11-28 11:06:12

标签: javascript backbone.js

我正在尝试将用户定义的回调绑定为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>
&#13;
&#13;
&#13;

点击&#34;点击我&#34;,它会从原型中提醒&#34; testClick!&#34;

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

1 个答案:

答案 0 :(得分:2)

因为以下行:

testClick: this.testClick.bind(this)

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

考虑这个例子:

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将在名为!&#34;的实例中显示&#34; testClick。

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

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