gpt4 book ai didi

javascript - 如何以及在何处初始化 Backbone View 中的 jquery 数据表

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:36:16 24 4
gpt4 key购买 nike

我的 html 模板如下所示:

   <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>

我的 Backbone 观点如下:

   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()) );
}
});

以上代码完美运行。现在,我想使用带有 Bootstrap 支持的应用 jquery 数据表插件。您可以在此处找到详细信息:http://www.datatables.net/blog/Twitter_Bootstrap_2所以,我只是在渲染中添加了一行:

        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);

},

现在,jquery 数据表还没有初始化。他们只是显示普通表格。

  • 我应该在哪里初始化表以应用 jquery 数据表?
  • 他们在没有主心骨的情况下也能完美地工作。

最佳答案

很可能,jQuery 插件需要页面上的元素才能工作。您不会在该 View 上显示调用 render 的位置,但我假设您正在做这样的事情:

var view = new PlayerView();
$('#foo').html(view.render().el); // this renders, then adds to page

如果这是真的,那么在 render 中使用插件还为时过早,因为 View 的 html 尚未添加到页面。

你可以试试这个:

var view = new PlayerView();
$('#foo').html(view.el); // add the view to page before rendering
view.render();

或者你可以试试这个:

var view = new PlayerView();
$('#foo').html(view.render().el);
view.setupDataTable(); // setup the jQuery plugin after rendering and adding to page

关于javascript - 如何以及在何处初始化 Backbone View 中的 jquery 数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15523237/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com