Reputation: 1965
How can I bind the click event after the deferred script is loaded?
I have a Kendo Grid (in Razor) with deferred initialization due performance issues. So all js scripts are included in the end of the document.
@(Html.Kendo().Grid<MyViewModel>()
.Name("myGrid")
.Columns(columns =>
{
columns.Bound(c => c.Name);
columns.Bound(c => c.City);
columns
.Bound(c => c.Id)
.Title("Commands")
.Sortable(false)
.Filterable(false)
.ClientTemplate(
"<a href='" + @Url.Action("Details", new { id = "#=Id#" }) +
"' class='btn btn-success' title='Details'>" +
"<span class='glyphicon glyphicon-list'></span></a>" +
"<a href='" + @Url.Action("Edit", new { id = "#=Id#" }) +
"' class='btn btn-info' title='Edit'>" +
"<span class='glyphicon glyphicon-pencil'></span></a>" +
"<a href='\\#' data-id='#=Id#' data-action='deactivate' " +
"class='btn btn-warning' title='Desactivate'>" +
"<span class='glyphicon glyphicon-remove-sign'></span></a>"
);
})
.Pageable()
.Sortable()
.Filterable()
.DataSource(ds => ds
.Ajax()
.Read(read => read.Action("ReadData", "MyController")).Sort(a => a.Add("Name")))
.Deferred()
)
Then I have a section at the end where I want to bind a click event to the <a>
click of every element which a data-action='deactivate'
attribute. The problem is the deffered initialization is performed after my document is ready.
@section scripts {
@Scripts.Render("~/bundles/kendo")
@Html.Kendo().DeferredScripts()
<script>
$(document).ready(function () {
$('[data-action="deactivate"]').click(function (event) {
var id = $(event.target).attr('data-id');
alert(id);
});
});
</script>
}
Upvotes: 1
Views: 1188
Reputation: 24738
Try using event delegation
http://learn.jquery.com/events/event-delegation/
$(document).on('click', '[data-action="deactivate"]'function (event) {
var id = $(event.target).attr('data-id');
alert(id);
});
In this way, the target DOM element does not have to exist when the event is bound.
Upvotes: 1