search

Home  >  Q&A  >  body text

javascript - backbone视图的model事件被重复绑定的问题

最近在用backbone开发项目时,遇到在model的change事件被重复绑定的问题。我在来回切换几次view(页面)的时候,change就会被重复绑定几次。
代码如下:

 var ItemView = Backbone.View.extend({
     tagName: 'p',
     className:'acc-item',
     initialize:function(opts){
        this.template = opts.mainView.itemTpl;
        this.dayView = opts.dayView;
        this.listenTo(this.model, 'destroy', this.remove);
        this.listenTo(this.model,'change',this.render);
     },
     render:function(){
        return this;
     },
     remove:function(){

    } 
});

请教一下,该怎么解决
巴扎黑巴扎黑2901 days ago326

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-04-10 14:52:44

    解决问题了,在initialize里面写this.model.off('change')和this.model.off('destroy')即可!

    reply
    0
  • ringa_lee

    ringa_lee2017-04-10 14:52:44

    Backbone View 自身有 remove 方法, 被楼主覆盖掉了.
    看一下里边做了什么: http://backbonejs.org/docs/backbone.html#section-136

    jsremove: function() {
      this.$el.remove();
      this.stopListening();
      return this;
    },
    

    reply
    0
  • Cancelreply