Reputation: 1203
I am trying to bind a user defined callback as Backbone's click event.
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!"
I am not sure why the alert from the instance is not getting called. What am I doing wrong here? Please help!
Upvotes: 0
Views: 197
Reputation: 144669
Because the following line:
testClick: this.testClick.bind(this)
detaches the testClick
function member of the Item
instance. 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!".
testClick: () => {
this.testClick();
}
This is because the above code calls the current .testClick
method of the Item instance.
Upvotes: 2