From ac2f1612718ae4474745ca8f25477d23f841f266 Mon Sep 17 00:00:00 2001 From: cmrd Senya Date: Thu, 14 Jul 2016 17:58:11 +0300 Subject: [PATCH] Fix views.js corner case --- app/assets/javascripts/app/views.js | 3 ++- spec/javascripts/app/views_spec.js | 34 +++++++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/app/assets/javascripts/app/views.js b/app/assets/javascripts/app/views.js index d5befff44..ebd8901a9 100644 --- a/app/assets/javascripts/app/views.js +++ b/app/assets/javascripts/app/views.js @@ -73,7 +73,8 @@ app.views.Base = Backbone.View.extend({ var self = this; _.each(this.subviews, function(property, selector){ var view = _.isFunction(self[property]) ? self[property]() : self[property]; - if(view) { + if (view && self.$(selector).length > 0) { + self.$(selector).empty(); self.$(selector).html(view.render().el); view.delegateEvents(); } diff --git a/spec/javascripts/app/views_spec.js b/spec/javascripts/app/views_spec.js index e11e4cdef..6992f0372 100644 --- a/spec/javascripts/app/views_spec.js +++ b/spec/javascripts/app/views_spec.js @@ -85,10 +85,40 @@ describe("app.views.Base", function(){ it("renders the sub views from functions", function(){ expect(this.view.$('.subview2').text().trim()).toBe("furreal this is the Second Subview"); }); + + context("with nested matching elements", function() { + var subviewInstance; + + beforeEach(function() { + var counter = 0; + var Subview = app.views.Base.extend({ + templateName: "static-text", + + className: "subview1", // making the internal view's div class match to the external one + + presenter: function() { + return {text: "rendered " + ++counter + " times"}; + } + }); + + this.view.templateName = false; // this is also important specification for the test below + this.view.subview1 = function() { + subviewInstance = new Subview(); + return subviewInstance; + }; + }); + + it("properly handles nested selectors case", function() { + this.view.render(); + this.view.render(); + subviewInstance.render(); + expect(this.view.$(".subview1 .subview1").text()).toBe("rendered 3 times"); + }); + }); }); - context("calling out to third party plugins", function(){ - it("replaces .time with relative time ago in words", function(){ + context("calling out to third party plugins", function() { + it("replaces .time with relative time ago in words", function() { spyOn($.fn, "timeago"); this.view.render(); expect($.fn.timeago).toHaveBeenCalled();