I'm trying to set up my collection to listen to events triggered on models within the collection, like so:
var Collection = Backbone.Collection.extend({
initialize: function() {
this.on('playback:completed', this.playNext);
},
playNext : function() { }
});
In my tests, I add new Backbone.Models into an instance of the collection, and then trigger playback:completed on them... and playNext isn't called. How do I set this up correctly?
EDIT: adding test code (uses Jasmine):
var collection;
describe('Collection', function() {
beforeEach(function() {
collection = new Collection();
});
it('should playNext when playback:completed is triggered', function() {
var model1 = new Backbone.Model();
var model2 = new Backbone.Model();
var spy = spyOn(collection, 'playNext').andCallThrough();
collection.add(model1);
collection.add(model2);
model1.trigger('playback:completed');
expect(spy).toHaveBeenCalled();
});
});
The problem here is that backbone's .on wraps the callback as a clone or something like it. Since the spy is set up after Collection.initialize runs, the callback that's been wrapped is the function before setting the spy, it's never triggered.
The solution I settled on was to pull the event bindings into a bindEvents function, like so:
var Collection = Backbone.Collection.extend({
initialize: function() {
this.bindEvents();
},
bindEvents : function() {
this.on('playback:completed', this.playNext);
},
playNext : function() { }
});
Then, in my test (and after the spy is set), I ran collection.off(); collection.bindEvents();, which re-binds them with the spied versions.
Related
I have a class like:
MyClass = function() {
var view = {
delegateEvents: function () {
this.$el.on('click', 'input[type="radio"]', this.toggleServices);
},
toggleServices: function () {
…
},
render: function () {
blah-blah-blag (rendering the view)…
this.delegateEvents();
}
};
view.init();
return view;
}
(how I am getting $el is beyond the scope of the question, but be sure it works)
I am testing an instance of this class in Jasmine like:
it('it handles clicks on radio buttons', function () {
var view = new MyClass();
view.render();
spyOn(view, 'toggleServices');
view.$('input[type="radio"]').eq(0).click();
expect(view.toggleServices).toHaveBeenCalled();
});
The problem is now that in the test, the spy is not being called, but the code goes into original toggleServices() of the class instead of being a spy. Seems like I don't understand how to create a spy that would cought requests to this.toggleServices in init().
Any suggestions?
You should spy before setup the listeners, in other words, just spy before call render.
it('it handles clicks on radio buttons', function () {
var view = new MyClass();
spyOn(view, 'toggleServices');
view.render();
view.$('input[type="radio"]').eq(0).click();
expect(view.toggleServices).toHaveBeenCalled();
});
Ok, so I am working on a method to override the fetch method on a model. I want to be able to pass it a list of URL's and have it do a fetch on each one, apply some processing to the results, then update its own attributes when they have all completed. Here's the basic design:
A Parent "wrapper" Model called AllVenues has a custom fetch function which reads a list of URL's it is given when it is instantiated
For each URL, it creates a Child Model and calls fetch on it specifying that URL as well as a success callback.
The AllVenues instance also has a property progress which it needs to update inside the success callback, so that it will know when all Child fetch's are complete.
And that's the part I'm having problems with. When the Child Model fetch completes, the success callback has no context of the Parent Model which originally called it. I've kind of hacked it because I have access to the Module and have stored the Parent Model in a variable, but this doesn't seem right to me. The Parent Model executed the Child's fetch so it should be able to pass the context along somehow. I don't want to hardcode the reference in there.
TL;DR
Here's my jsFiddle illustrating the problem. The interesting part starts on line 13. http://jsfiddle.net/tonicboy/64XpZ/5/
The full code:
// Define the app and a region to show content
// -------------------------------------------
var App = new Marionette.Application();
App.addRegions({
"mainRegion": "#main"
});
App.module("SampleModule", function (Mod, App, Backbone, Marionette, $, _) {
var MainView = Marionette.ItemView.extend({
template: "#sample-template"
});
var AllVenues = Backbone.Model.extend({
progress: 0,
join: function (model) {
this.progress++;
// do some processing of each model
if (this.progress === this.urls.length) this.finish();
},
finish: function() {
// do something when all models have completed
this.progress = 0;
console.log("FINISHED!");
},
fetch: function() {
successCallback = function(model) {
console.log("Returning from the fetch for a model");
Mod.controller.model.join(model);
};
_.bind(successCallback, this);
$.each(this.urls, function(key, val) {
var venue = new Backbone.Model();
venue.url = val;
venue.fetch({
success: successCallback
});
});
}
});
var Venue = Backbone.Model.extend({
toJSON: function () {
return _.clone(this.attributes.response);
}
});
var Controller = Marionette.Controller.extend({
initialize: function (options) {
this.region = options.region;
this.model = options.model;
this.listenTo(this.model, 'change', this.renderRegion);
},
show: function () {
this.model.fetch();
},
renderRegion: function () {
var view = new MainView({
model: this.model
});
this.region.show(view);
}
});
Mod.addInitializer(function () {
var allVenues = new AllVenues();
allVenues.urls = [
'https://api.foursquare.com/v2/venues/4a27485af964a52071911fe3?oauth_token=EWTYUCTSZDBOVTYZQ3Z01E54HMDYEPZMWOC0AKLVFRBIEXV4&v=20130811',
'https://api.foursquare.com/v2/venues/4afc4d3bf964a520512122e3?oauth_token=EWTYUCTSZDBOVTYZQ3Z01E54HMDYEPZMWOC0AKLVFRBIEXV4&v=20130811',
'https://api.foursquare.com/v2/venues/49cfde17f964a520d85a1fe3?oauth_token=EWTYUCTSZDBOVTYZQ3Z01E54HMDYEPZMWOC0AKLVFRBIEXV4&v=20130811'
];
Mod.controller = new Controller({
region: App.mainRegion,
model: allVenues
});
Mod.controller.show();
});
});
App.start();
I think you're misunderstanding how _.bind works. _.bind returns the bound function, it doesn't modify it in place. In truth, the documentation could be a bit clearer on this.
So this:
_.bind(successCallback, this);
is pointless as you're ignoring the bound function that _.bind is returning. I think you want to say this:
var successCallback = _.bind(function(model) {
console.log("Returning from the fetch for a model");
Mod.controller.model.join(model);
}, this);
Also note that I added a missing var, presumably you don't want successCallback to be global.
I had a strange issue working with backbone and binding events. I'll see if I can explain it in a clear way (it's a cropped example...)
In a view, I had the following code in the initialize method
var MyView = Backbone.View.extend({
initialize: function(options) {
//[...]
this.items = [];
this.collection.on('reset', this.updateItems, this);
this.fetched = false;
},
render: function() {
if (!this.fetched) {
this.collection.fetch(); // fetch the collection and fire updateItems
return this;
}
this.$el = $('#my-element');
this.$el.html(this.template(this.items));
},
updateItems: function() {
this.fetched = true;
this.loadItems();
this.render(); // call render with the items array ready to be displayed
}
}
The idea is that I have to fetch the collection, process the items (this.loadItems), and then I set this.$el.
The problem I was facing, is that inside updateItems, I couldn't see any property added after the binding (this.collection.on...)
It seemed like the binding was done against a frozen version of the view. I tried adding properties to test it, but inside updateItems (and inside render if being fired by the collection reset event) I could not see the added properties.
I solved it binding the collection just before fetching it, like this:
render: function() {
if (!this.fetched) {
this.collection.on('reset', this.updateItems, this);
this.collection.fetch();
return this;
}
But it's a strange behavior. Seems like when binding, a copy of 'this' is made, instead of a reference.
Am I right? or there's anything wrong I'm doing?
You should perform your binding in the initialization phase of your collection view:
// View of collection
initialize: function() {
this.model.bind('reset', this.updateItems);
}
now when fetch is finished on the collection updateItems method will be invoked.
Of course you need to bind the model and view before doing this:
var list = new ListModel();
var listView = new ListView({model: list});
list.fetch();
I'm testing a backbone view with Jasmin, Simon and jasmin-simon.
Here is the code:
var MessageContainerView = Backbone.View.extend({
id: 'messages',
initialize: function() {
this.collection.bind('add', this.addMessage, this);
},
render: function( event ) {
this.collection.each(this.addMessage);
return this;
},
addMessage: function( message ) {
console.log('addMessage called', message);
var view = new MessageView({model: message});
$('#' + this.id).append(view.render().el);
}
});
Actually, all my tests pass but one. I would like to check that addMessage is called whenever I add an item to this.collection.
describe('Message Container tests', function(){
beforeEach(function(){
this.messageView = new Backbone.View;
this.messageViewStub = sinon.stub(window, 'MessageView').returns(this.messageView);
this.message1 = new Backbone.Model({message: 'message1', type:'error'});
this.message2 = new Backbone.Model({message: 'message2', type:'success'});
this.messages = new Backbone.Collection([
this.message1, this.message2
]);
this.view = new MessageContainerView({ collection: this.messages });
this.view.render();
this.eventSpy = sinon.spy(this.view, 'addMessage');
this.renderSpy = sinon.spy(this.messageView, 'render');
setFixtures('<div id="messages"></div>');
});
afterEach(function(){
this.messageViewStub.restore();
this.eventSpy.restore();
});
it('check addMessage call', function(){
var message = new Backbone.Model({message: 'newmessage', type:'success'});
this.messages.add(message);
// TODO: this fails not being called at all
expect(this.view.addMessage).toHaveBeenCalledOnce();
// TODO: this fails similarly
expect(this.view.addMessage).toHaveBeenCalledWith(message, 'Expected to have been called with `message`');
// these pass
expect(this.messageView.render).toHaveBeenCalledOnce();
expect($('#messages').children().length).toEqual(1);
});
});
As you can see addMessage is called indeed. (It logs to the console and it calls this.messageView as it should. What do I miss in spying for addMessage calls?
thanks, Viktor
I'm not quit sure but, as I understand it, the following happens:
You create a new view which calls the initialize function and bind your view.addMessage to your collection.
Doing this, Backbone take the function and store it in the event store of your collection.
Then you spy on view.addMessage which means you overwrite it with a spy function. Doing this will have no effect on the function that is stored in the collection event store.
So their are some problems with your test. You view has a lot of dependencies that you not mock out. You create a bunch of additional Backbone Models and Collections, which means you not test only your view but also Backbones Collection and Model functionality.
You should not test that collection.bind will work, but that you have called bind on the collection with the parameters 'add', this.addMessage, this
initialize: function() {
//you dont
this.collection.bind('add', this.addMessage, this);
},
So, its easy to mock the collection:
var messages = {bind:function(){}, each:function(){}}
spyOn(messages, 'bind');
spyOn(messages, 'each');
this.view = new MessageContainerView({ collection: messages });
expect(message.bind).toHaveBeenCalledWith('bind', this.view.addMessage, this.view);
this.view.render()
expect(message.each).toHaveBeenCalledWith(this.view.addMessage);
... and so on
Doing it this way you test only your code and have not dependencies to Backbone.
As Andreas said in point 3:
Then you spy on view.addMessage which means you overwrite it with a spy function. Doing this will have no effect on the function that is stored in the collection event store.
The direct answer to the question, disregarding all the awesome refactoring Andreas suggested, would be to spy on MessageContainerView.prototype.addMessage like so:
describe('Message Container tests', function(){
beforeEach(function(){
this.messageView = new Backbone.View;
this.messageViewStub = sinon.stub(window, 'MessageView').returns(this.messageView);
this.message1 = new Backbone.Model({message: 'message1', type:'error'});
this.message2 = new Backbone.Model({message: 'message2', type:'success'});
this.messages = new Backbone.Collection([
this.message1, this.message2
]);
// Here
this.addMessageSpy = sinon.spy(MessageContainerView.prototype, 'addMessage');
this.view = new MessageContainerView({ collection: this.messages });
this.view.render();
this.eventSpy = sinon.spy(this.view, 'addMessage');
this.renderSpy = sinon.spy(this.messageView, 'render');
setFixtures('<div id="messages"></div>');
});
afterEach(function(){
this.messageViewStub.restore();
MessageContainerView.prototype.addMessage.restore();
});
it('check addMessage call', function(){
var message = new Backbone.Model({message: 'newmessage', type:'success'});
this.messages.add(message);
// TODO: this fails not being called at all
expect(this.addMessageSpy).toHaveBeenCalledOnce();
// TODO: this fails similarly
expect(this.addMessageSpy).toHaveBeenCalledWith(message, 'Expected to have been called with `message`');
// these pass
expect(this.messageView.render).toHaveBeenCalledOnce();
expect($('#messages').children().length).toEqual(1);
});
});
Regardless, I do recommend implementing Andreas' suggestions. :)
I have a Backbone View for a general element that specific elements will be inheriting from. I have event handling logic that needs to be applied to all elements, and event handling logic that is specific to child-type elements. I'm having trouble because a child View has its own callback for an event that is also handled by the parent View, and so when I try to use the events hash in both, either the child or parent callback is never called. Let me illustrate with some code:
var ElementView = Backbone.View.extend({
events: {
"mouseup": "upHandler",
"mousedown": "downHandler",
"mousemove": "moveHandler"
},
initialize: function() {
// add events from child
if (this.events)
this.events = _.defaults(this.events, ElementView.prototype.events);
this.delegateEvents(this.events);
}
});
var StrokeView = ElementView.extend({
events: {
"mousemove": "strokeMoveHandler"
}
});
How would I solve this in an extensible way, especially if I will later have another level of inheritance?
One way to handle this would be to use "namespaces" for events:
var ElementView = Backbone.View.extend({
events: {
"mouseup.element": "upHandler",
"mousedown.element": "downHandler",
"mousemove.element": "moveHandler"
},
initialize: function() {
// add events from child
if (this.events)
this.events = _.defaults(this.events, ElementView.prototype.events);
this.delegateEvents(this.events);
}
});
var StrokeView = ElementView.extend({
events: {
"mousemove.strokeview": "strokeMoveHandler"
}
});
In fact, this approach is suggested in Backbone.js documentation.
I've done something similiar by taking advantage of JavaScript's faux-super as mentioned in the Backbone.js documentation and the initialization function
var ElementView = Backbone.View.extend({
events: {
"mouseup": "upHandler",
"mousedown": "downHandler",
"mousemove": "moveHandler"
},
initialize: function() {
this.delegateEvents();
}
});
var StrokeView = ElementView.extend({
initialize: function() {
this.events = _.extend({}, this.events, {
"mousemove": "strokeMoveHandler"
});
// Call the parent's initialization function
ElementView.prototype.initialize.call(this);
}
});
var SubStrokeView = StrokeView.extend({
initialize: function() {
this.events = _.extend({}, this.events, {
"click": "subStrokeClickHandler",
"mouseup": "subStrokeMouseupHandler"
});
// Call the parent's initialization function
StrokeView.prototype.initialize.call(this);
}
});
var c = new SubStrokeView();
console.log(c.events);
// Should be something like
// click: "subStrokeClickHandler"
// mousedown: "downHandler"
// mousemove: "strokeMoveHandler"
// mouseup: "subStrokeMouseupHandler"
The magic happens by setting the events within the initialize function. If you have multiple events attributes in your prototypes, JavaScript will only see the one set most recently due to how prototyping works.
Instead, by doing it this way, each view sets its own this.events, then calls its parent's initialize function which in turn extends this.events with its events, and so on.
You do need to set this.events in this specific way:
this.events = _.extend({}, this.events, ...new events...);
instead of
_.extend(this.events, ...new events...);
Doing it the second way will munge the events object within the parent's (ElementView) prototype. The first way ensures each model gets its own copy.