The problem of defining the function within an anonymous function is that it will only belong to the context of this function, and will cease to exist when the anonymous function has finished executing. If the issue is just calling the function within the anonymous function that treats the event done
, you can define the desired function in a wider context and just call it, as the example below.
$(function () {
function minhaFuncao() {
alert("ok");
}
$.connection.hub.start().done(function () {
minhaFuncao();
});
});
In this way, minhaFuncao
is defined in a larger context, existing anywhere within the code $(function () {...});
jQuery.
The following example was produced only to show the working of the above logic here in Sopt, since it could not reproduce the event $.connection.hub.start().done
, since it depends on third party plugins.
To see in operation, just make a simpler example:
function minhaFuncao() {
alert("ok");
}
$(function () {
minhaFuncao();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The function itself defined as jQuery context is an anonymous function. By defining its function in the global context, it will also exist there. When the page has the DOM loaded, an alert will be displayed.
Why is the function set there? The problem that by defining it within an anonymous function, it ceases to exist when it finishes running. That is, when you make the call, it will not exist, giving the error. There is no explanation for defining it within the event
done
.– Woss
@Matheusmiranda Why don’t you do otherwise? Set her off
done
and call it callback after without rewriting it.– Leonardo Pessoa