Backbonejs查看自我模板replaceWith和事件

我正在使用bbjs开发我的第一个应用程序,经过10个教程和无穷无尽的资源我试图想出我的代码设计。

我问有什么是视图和模板的最佳实践。 还有一个我正在努力解决的事件问题。 据我了解,视图是负责一个元素及其内容(和其他子视图)。 对于可管理,可测试等的代码,元素/模板将在创建时传递给视图。 在我的应用程序Imho中,视图应该包含模板,因为可见元素具有许多“状态”和每个状态的不同模板。 当状态发生变化时,我认为最好创建一个新视图,但是,视图是否可以使用新元素更新自身?

App.Box = Backbone.Model.extend({ defaults: function() { return { media: "http://placehold.it/200x100", text: "empty...", type: "type1" }; } }); App.BoxView = Backbone.View.extend({ template: {}, templates: { "type1": template('appboxtype1'), "type2": template('appboxtype2') }, events: { 'click .button': 'delete' }, initialize: function(options) { this.listenTo(this.model, 'change', this.render); this.listenTo(this.model, 'destroy', this.remove); this.render(); }, render: function() { this.template = this.templates[ this.model.get("type") ]; // first method this.$el.replaceWith( $($.parseHTML(this.template(this))) ); this.$el.attr("id", this.model.cid); // second method var $t_el = this.$el; this.setElement( $($.parseHTML(this.template(this))) ); this.$el.attr("id", this.model.cid); $t_el.replaceWith( this.$el ); this.delegateEvents(); //$('#'+this.model.cid).replaceWith( $(g.test.trim()) ); //! on the second render the events are no longer bind, deligateEvents doesn't help return this; }, // get values text: function() { return this.model.get('text'); }, media: function() { return this.model.get('media'); }, delete: function() { this.model.destroy(); } }); 

感谢名单! 🙂

而不是尝试替换视图的根元素($ el),只需替换其内容即可。

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

事件应该仍然有效。

我提出了这个解决方案: http : //jsfiddle.net/Antonimo/vrQzF/4/

如果有人有更好的主意,它总是受欢迎!

基本上,在视图中:

  var t_$el = this.$el; this.$el = $($.parseHTML(this.template(this))); this.$el.attr("id", this.cid); if (t_$el.parent().length !== 0) { // if in dom this.undelegateEvents(); t_$el.each(function(index, el){ // clean up if( index !== 0 ){ $(el).remove(); } }); t_$el.first().replaceWith(this.$el); this.delegateEvents(); } 

试试这个

 render: function() { html = '
your new html
'; var el = $(html); this.$el.replaceWith(el); this.setElement(el); return this; }

$ .replaceWith只会替换DOM中的元素。 但是这个。$ el仍然提到了现在流离失所的旧元素。 你需要调用this.setElement(..)来更新这个。$ el字段。 调用setElement还会为您执行undelegateEvents和delegateEvents事件。