Pregunta

I have the following script for my SignalR hub and I'm having trouble on calling my function so that I can pass a parameter through.

$(function () {
    var hub = $.connection.commentsHub;

    $.connection.hub.start().done(function () {
        function deleteComment(commentId) {
            hub.server.DeleteComment(commentId);
        }
    });
});

And then in my list of comments I am trying to call my deleteComment function with this but I get an error stating that deleteComment is not defined.

<a onclick="deleteComment(@item.CommentId)">Delete</a>

How do I call my deleteComment function?

Or, is there a better way to pass the parameter to my server?

¿Fue útil?

Solución

Your deleteComment() function is buried within two layers of other functions, so there's no way your inline JavaScript can access it. I suggest (1) taking it out of your done callback because there's no reason for it to be there and (2) using unobtrusive JavaScript for this:

HTML:

<a href="#" class="delete-comment" data-commentid="@item.CommentId">Delete</a>

JavaScript:

$(function () {
    var hub = $.connection.commentsHub;

    function deleteComment(commentId) {
        hub.server.DeleteComment(commentId);
    }

    $.connection.hub.start().done(function () {
        $(".delete-comment").click(function() {
            deleteComment($(this).attr("data-commentid"));
        });
    });
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top