My html template look like this:
<script type="text/template" id="players-template">
<table id="example" class="table table-striped table-bordered table-condensed table-hover">
<thead>
<tr>
<th>Name</th>
<th>group</th>
<th></th>
</tr>
</thead>
<tbody id="playersTable"></tbody>
</table>
</script>
<script type="text/template" id="player-list-item-template">
<td><@= name @></td>
<td>
<@ _.each(hroups, function(group) { @>
<@= group.role @>
<@ }); @>
</td>
</script>
My backbone view is as follows:
playerView = Backbone.View.extend({
template: _.template( $("#player-template").html() ),
initialize: function ()
if(this.collection){
this.collection.fetch();
},
render: function () {
this.$el.html( this.template );
this.collection.each(function(player) {
var itemView = new app.PlayerListItemView({ model: player });
itemView.render();
this.$el.find('#playersTable').append(itemView.$el);
},this
});
// view to generate each player for list of players
PlayerListItemView = Backbone.View.extend({
template: _.template($('#player-list-item-template').html()),
tagName: "tr",
render: function (eventName) {
this.$el.html( this.template(this.model.toJSON()) );
}
});
The above code works perfectly. Now, I want to use apply jquery datatable plugin wtih bootstrap support. You can find detail here :http://www.datatables.net/blog/Twitter_Bootstrap_2 So, I just added the line inside render as:
render: function () {
this.$el.html( this.template );
this.collection.each(function(player) {
var itemView = new app.PlayerListItemView({ model: player });
itemView.render();
this.$el.find('#playersTable').append(itemView.$el);
$('#example').dataTable( {
console.log('datatable');
"sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i> <'span6'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_ records per page"
},
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [ 2 ] }
]
} );
},this);
},
Now, the jquery datable is not initialized. They just diisplay normal table.
- where should I intialized the table to apply jquery datatable?
- they worked perfectly without backbone.
Most likely, the jQuery plugin needs the elements to be on the page to work. You don't show where you are calling render
on that view, but I am going to assume you are doing something like this:
var view = new PlayerView();
$('#foo').html(view.render().el); // this renders, then adds to page
If this is true, then using the plugin inside render is too early, since the view's html is not yet added to the page.
You can try this:
var view = new PlayerView();
$('#foo').html(view.el); // add the view to page before rendering
view.render();
Or you can try this:
var view = new PlayerView();
$('#foo').html(view.render().el);
view.setupDataTable(); // setup the jQuery plugin after rendering and adding to page
来源:https://stackoverflow.com/questions/15523237/how-and-where-to-initialize-jquery-datatable-in-backbone-view