0
var foo = Backbone.View.extend({    
  tagName: 'div',
  className: 'unselected',
  events: {
    'click div' : 'select'
  },  
  initiate: function () {
    ._bindall(this, 'render' , 'select' );    
    this.render();
  },
  render: function () {
    $(this.el).html(_.template($("#template").html(),{...});
    return this;
  },
  select: function () {
    if ( this.className == 'selected' ) {
      this.className = 'unselected';
    }
    else {
      this.className = 'selected';
    }
    this.render();
  }
});

当我单击此 div 框时,className 已正确更新,但 html 未更新。因此,视图的 className 将更改为“selected”,但是当我检查网页上的 div 框元素时,它仍然显示为“class="unselected"。” 我也希望在单击时更新 html。

建议或指向教程/文档的链接将不胜感激。

4

2 回答 2

1

Backbone.Views 只是一个方便的占位符——不是实际的 DOMElements。您需要this.el通过以下方式进行更新:

select: function () {

  if ( this.className == 'selected' ) {
    this.className = 'unselected';
  }
  else {
    this.className = 'selected';
  }
  this.el.className = this.className;
  this.render();
}
于 2012-07-11T21:20:47.433 回答
1

您可能想要做的是在 el 选择器本身上执行此操作,并使用链接的 jquery toggleClass 调用。您可以在一行中完成所有操作:

select : function() {
    this.$el.toggleClass('selected').toggleClass('unselected');
}

快捷方便...

于 2012-07-12T00:18:59.123 回答