Skip to content
Browse files

Add 'swapped' method / event to composite_view

Allows for triggering events when the new view is added to the DOM

- SwappingRouter calls the swapped method if it exists
- CompositeView emits 'swapped' event

Closes pull request #11 - 'Add a call when the view has been swapped'
  • Loading branch information...
1 parent a5f6c26 commit 5a1debe3f71646ecd88258076bf761b8e9a69f5b @christoomey christoomey committed Apr 26, 2013
View
4 lib/assets/javascripts/backbone-support/composite_view.js
@@ -44,6 +44,10 @@ _.extend(Support.CompositeView.prototype, Backbone.View.prototype, Support.Obser
this.$(container).prepend(view.el);
},
+ swapped: function () {
+ this.trigger('swapped')
+ },
+
_leaveChildren: function() {
this.children.chain().clone().each(function(view) {
if (view.leave)
View
4 lib/assets/javascripts/backbone-support/swapping_router.js
@@ -10,6 +10,10 @@ _.extend(Support.SwappingRouter.prototype, Backbone.Router.prototype, {
this.currentView = newView;
$(this.el).empty().append(this.currentView.render().el);
+
+ if (this.currentView && this.currentView.swapped) {
+ this.currentView.swapped();
+ }
}
});
View
13 spec/javascripts/composite_view_spec.js
@@ -246,6 +246,18 @@ describe("Support.CompositeView", function() {
});
});
+ describe("#swapped", function() {
+ it("fires 'swapped' event", function() {
+ var eventListener = sinon.spy()
+ var view = new Support.CompositeView
+ view.bind('swapped', eventListener)
+
+ view.swapped();
+
+ expect(eventListener.called).toBeTruthy();
+ });
+ });
+
describe("#bindTo", function() {
var view = new orangeView();
var callback = sinon.spy();
@@ -287,5 +299,4 @@ describe("Support.CompositeView", function() {
});
});
});
-
});
View
18 spec/javascripts/swapping_router_spec.js
@@ -16,8 +16,8 @@ describe("Support.SwappingRouter", function() {
});
var leaveView = Backbone.View.extend({
- leave: function() {
- }
+ leave: function() {},
+ swapped: function() {},
});
var leaveViewInstance = new leaveView();
@@ -119,4 +119,18 @@ describe("Support.SwappingRouter", function() {
expect(spy.called).toBeTruthy();
});
});
+
+ it("calls .swapped on the view after swapping", function() {
+ var spy = sinon.spy(leaveViewInstance, "swapped");
+
+ runs(function() {
+ window.location.hash = "#leave"
+ });
+
+ Helpers.sleep()
+
+ runs(function() {
+ expect(spy.called).toBeTruthy()
+ });
+ });
});

0 comments on commit 5a1debe

Please sign in to comment.
Something went wrong with that request. Please try again.