Backbone.js:更改view.attributes不会反映在view.el上



我有一个类似的主干视图

 window.InputView = Backbone.View.extend({
        tagName:'input',
        className:'',
        attributes:{},
        initialize:function(){
            this.attributes=this.model.attributes;
            this.el = this.make(this.tagName,this.attributes,'');
        }
    });

我遇到的问题是,当我修改视图的attributes哈希时,它不会反映在el、上

所以我必须做一些类似this.el = this.make(this.tagName,this.attributes,'');的事情以便反映变化。

这是唯一的方法,还是有更好的方法?比如自动化?

要在模型更改时自动执行您试图执行的操作,需要将方法绑定到模型的更改事件。在初始化方法中,您需要以下内容:

initialize: function() {
    this.model.on("change", updateElement);
    ...
}

然后在以后的视图中定义该方法:

updateElement: function() {
    //use this.model.attributes to update your el
}

现在,只要与该视图关联的模型发生更改,updateElement方法就会运行。

您只是覆盖了视图的el属性,我认为这不是您想要的。如下所示,make函数不会将新创建的元素附加到DOM,因此它不会出现,并且不会从页面中删除旧元素。

一种可能的解决方法:

initialize: function(){
  this.attributes = this.model.attributes; // why are you doing this anyway? :)
  var $oldEl = this.$el; // backbone 0.91
  var newEl = this.make(this.tagName,this.attributes,'');
  $oldEl.after( newEl ); // the old element must be in the DOM, when doing this!
  $oldEl.remove();
  this.setElement( newEl ); // proper setup
}

BackBone的报价来源:

make: function(tagName, attributes, content) {
  var el = document.createElement(tagName);
  if (attributes) $(el).attr(attributes);
  if (content) $(el).html(content);
  return el;
},
setElement: function(element, delegate) {
  this.$el = $(element);
  this.el = this.$el[0];
  if (delegate !== false) this.delegateEvents();
  return this;
},

最新更新