Reputation: 15070
I want to create a JavaScript class that has an onclick event handler as a method:
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function () {
var foo = new Foo();
foo.load();
});
function Foo() {
function clicked() {
alert('clicked');
}
this.load = function () {
$('#container').html('<button onclick="clicked()">Press</button>');
}
}
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
But I get a scope error: Uncaught ReferenceError: clicked is not defined.
Why? How do I fix the scope and keep the event handler as a method of the class?
Upvotes: 0
Views: 65
Reputation: 32202
Create the button as an object, and assign the click handler directly:
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function () {
var foo = new Foo();
foo.load();
});
function Foo() {
function clicked() {
alert('clicked');
}
this.load = function () {
var b = $('<button>');
b.text('Press');
b.on('click', clicked);
$('#container').append(b);
}
}
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
Doing it this way keeps a reference directly to the function itself, as it's always in scope. By assigning it through the onclick
attribute, it loses the scope of where it was declared.
Upvotes: 2
Reputation: 960
Try this
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function () {
foo.load();
});
var foo = new Foo();
function Foo()
{
this.clicked=clicked;
function clicked()
{
alert('clicked');
}
this.load = function ()
{
$('#container').html('<button onclick="foo.clicked();">Press</button>');
}
}
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
Upvotes: 0
Reputation: 25164
You can avoid this by making a direct link to the function:
$('#container').html('<button>Press</button>').find('button').click(clicked);
Upvotes: 0