刷新collection.fetch()方法的表视图 [英] Refresh the table view on collection.fetch() method

查看:236
本文介绍了刷新collection.fetch()方法的表视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下情形: -

- 的模型播放器

  VAR球员= Backbone.Model.extend({
         默认值:{
PlayerId:0,
参赛者姓名: ,
IsActive:假的
}
    });

系列型号如下:

  VAR PlayerList = Backbone.Collection.extend({
            型号:播放机,
            网址:'/匹配/ GetPlayers /
        });

列表视图如下:

  VAR的ListView = Backbone.View.extend({
        EL:#ListContainer',
        初始化:功能(){
            _.bindAll(这一点,'渲染');
            this.collection.on(复位,this.render);
        },
        渲染:功能(){
            如果(this.collection.length大于0){
            this.collection.each(this.AppendPlayer,这一点);
            }
            返回此;
        },
        AppendPlayer:功能(数据){
            VAR palyerView =新PlayerView({模型:数据});
            $(this.el).find('表')追加(genreView.render()EL)。        },
        事件:{
            点击#btnplay:的checkStatus
        },        的checkStatus:功能(){            //警报();
           //这里我会做出Ajax调用,并得到更新播放器的状态
             这是从其他REST服务。
        }
    });

下面是PlayerView:

  VAR PlayerView = Backbone.View.extend({
        标签名:TR,
        模板:_.template($(#球员模板)HTML()),
        渲染:功能(){            这$ el.html(this.template(this.model.toJSON()));        返回此;
    }
    });

HTML如下:

 < D​​IV ID =ListContainer>
    <输入类型=按钮ID =btnplayVALUE =StatusCheck/>
    <表ID =myTable的>
        &所述; TR>
            < TD>玩家ID< / TD>
            < TD>名称和LT; / TD>
            < TD> Statu< / TD>
        < / TR>    < /表>
< / DIV>
< BR />
< BR /><脚本ID ='播放器模板类型='文本/模板'>
    &所述; TD>&下;%= PlayerId%GT;&下; / TD>
    &所述; TD>&下;%= PlayerName%GT;&下; / TD>
    &所述; TD>&下;%= IsActive%GT;&下; / TD>
< / SCRIPT>

所以当我点击播放按钮,它调用我的API服务,让我一个更新的集合。

和我尝试刷新收集并使用下面的逻辑视图:

  PlayerList.fetch({
                    成功:函数(收集,RESP){
                        //console.log('success'+ RESP); //                    },
                    错误:函数(ER){
                        的console.log('错误:%O',ER)
                    },
                    复位:真实,                });

我得到更新后的模型回来,但什么情况是更新模型中获取的与现有的行追加。

我要与我的新集合来清除现有的行和重新填充它。

任何帮助将是巨大的。


解决方案

空() 渲染方法内表:

 渲染:功能(){
  这$ el.find('表'),空()。 //清除现有行
  如果(this.collection.length大于0){
     this.collection.each(this.AppendPlayer,这一点);
  }
  返回此;
}


顺便说一句,你不必做 $(this.el),通过骨干为您的视图元素的jQuery的实例,这一点。 $埃尔

除非你重用 AppendPlayer (我建议使用驼峰方法名称仅用于构造函数使用Pascal大小写)方法,你可以简单地做了以下内容:

 渲染:功能(){
  VAR $表=本$ el.find('表')。
  $ table.empty();
  如果(this.collection.length){
    this.collection.each(函数(模型){
      $ table.append(新PlayerView({
        型号:型号
      })渲染()EL)。
    });
  }
  返回此;
}

如果你修改playerView来表现自己,如下所示:

  VAR PlayerView = Backbone.View.extend({
  标签名:TR,
  模板:_.template($(#球员模板)HTML()),
  初始化:功能(){
    this.render();
  },
  渲染:功能(){
    这$ el.html(this.template(this.model.toJSON()));
    返回此;
  }
});

您可以这样做:

 渲染:功能(){
  VAR $表=本$ el.find('表')。
  $ table.empty();
  如果(this.collection.length){
    this.collection.each(函数(模型){
      $ table.append(新PlayerView({
        型号:型号
      })EL);
    });
  }
  返回此;
}


旁注:你似乎是创建 palyerView 但你要追加 genreView ..

Consider following Scenario:-

- Model of a Player

 var Player = Backbone.Model.extend({
         defaults: {
PlayerId: 0,
PlayerName: "",
IsActive: false
}
    });

Collection Model is as follows:

 var PlayerList = Backbone.Collection.extend({
            model: Player,
            url: '/Match/GetPlayers/'
        });

List View is as follows:

 var ListView = Backbone.View.extend({
        el: '#ListContainer',
        initialize: function () {
            _.bindAll(this, 'render');
            this.collection.on('reset', this.render);


        },
        render: function () {
            if (this.collection.length > 0) {
            this.collection.each(this.AppendPlayer, this);
            }
            return this;
        },
        AppendPlayer: function (data) {
            var palyerView= new PlayerView({ model: data });
            $(this.el).find('table').append(genreView.render().el);

        },
        events: {
            "click #btnplay": "CheckStatus"
        },

        CheckStatus: function () {

            // alert();
           //here i will make a ajax call and get update the status of player
             which comes from other REST service.
        }


    });

Below is the PlayerView:

var PlayerView = Backbone.View.extend({
        tagName: "tr",            
        template: _.template($("#player-Template").html()),
        render: function () {

            this.$el.html(this.template(this.model.toJSON()));

        return this;
    }
    });

HTML is as follows:

<div id="ListContainer">
    <input type="button" id="btnplay" value="StatusCheck" />
    <table id="myTable">
        <tr>
            <td>Player Id</td>
            <td>Name</td>
            <td>Statu</td>
        </tr>

    </table>
</div>
<br />
<br />

<script id='player-Template' type='text/template'>
    <td><%=PlayerId%></td>
    <td><%=PlayerName%></td>    
    <td><%=IsActive%></td> 
</script>

so when i click the "Play" button it calls my API service and gets me an updated collection.

and i try to refresh the collection and the view using below logic:

PlayerList.fetch({
                    success: function (collection, resp) {
                        //console.log('success' + resp); //

                    },
                    error: function (er) {
                        console.log('error: %o', er)
                    },
                    reset: true,

                });

I get the updated model back but what happen is the updated model get's appended with the existing rows.

I need to clear the existing rows and repopulate it with my new collection.

Any help would be great.

解决方案

empty() the table inside the render method:

render: function () {
  this.$el.find('table').empty(); // clears existing rows 
  if (this.collection.length > 0) {
     this.collection.each(this.AppendPlayer, this);
  }
  return this;
}


BTW, you don't have to do $(this.el), backbone provides a jQuery instance of your view's element via this.$el.

Unless you're reusing the AppendPlayer (I suggest using camelCase for method names. Use pascal case only for constructor functions) method, you can simply do the following:

render: function() {
  var $table = this.$el.find('table');
  $table.empty();
  if (this.collection.length) {
    this.collection.each(function(model) {
      $table.append(new PlayerView({
        model: model
      }).render().el);
    });
  }
  return this;
}

and if you modify the playerView to render itself as shown below:

var PlayerView = Backbone.View.extend({
  tagName: "tr",
  template: _.template($("#player-Template").html()),
  initialize: function() {
    this.render();
  },
  render: function() {
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  }
});

You can just do:

render: function() {
  var $table = this.$el.find('table');
  $table.empty();
  if (this.collection.length) {
    this.collection.each(function(model) {
      $table.append(new PlayerView({
        model: model
      }).el);
    });
  }
  return this;
}


Side note: you seems to be creating palyerView but you're appending genreView ..?!

这篇关于刷新collection.fetch()方法的表视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆