简体   繁体   English

骨干事件回调绑定

[英]Backbone event callback bind

I am trying to bind a user defined callback as Backbone's click event. 我正在尝试将用户定义的回调绑定为Backbone的click事件。

 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> 

Clicking on "Click me", it alerts "testClick from prototype called!" 点击“点击我”,它会警告“来自原型的testClick!”

I am not sure why the alert from the instance is not getting called. 我不确定为什么没有调用实例的警报。 What am I doing wrong here? 我在这里做错了什么? Please help! 请帮忙!

Because the following line: 因为下面这行:

testClick: this.testClick.bind(this)

detaches the testClick function member of the Item instance. 分离 Item实例的testClick函数成员。 You are essentially reusing a function and there is no linkage between the 2 methods. 您实质上是在重用一个函数,并且这两种方法之间没有链接。

Consider this example: 考虑以下示例:

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!'

If you use the following syntax the alert will show "testClick from instance called!". 如果您使用以下语法,则alert将显示“来自实例的testClick!”。

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

This is because the above code calls the current .testClick method of the Item instance. 这是因为上面的代码调用了Item实例的当前.testClick方法。

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

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