Unable to wrap functions assigned with events parameter in backbone model - backbone.js

Motivation: I want to wrap all functions within backbone model with log functionality to make it more easy to follow function calls.
I am iterating over models functions and warping them with underscores wrap().
But it looks like event function bindings from 'events' hash doesn't get wrapped as it looks like these functions are copied and stored somewhere in DOM, not sure.
Has anybody came to this problem as well or any ideas how to workaround?
Manually entering console.log() in these function is not what I am looking for.

I think you're experiencing the same problem as when people are trying to test the functionality provided with the events -hash. Spying on the event callback directly on the View doesn't work, but spying on the class prototype before instantiating works.
// This won't work
var view = new SomeView();
spyOn(view, 'onClick');
view.$el.click(); // spy isn't called
// This works
spyOn(SomeView.prototype, 'onClick');
var view = new SomeView();
view.$el.click(); // spy is called
Try iterating over the prototype of your 'class' right after creating it, because that should be where the methods called by the events -implementation should reside.

Related

How to access helpers in controller and why is my find() empty?

I'm pretty new to the new meteor 1.3.1. So I've never worked with helpers before.
This is my helper:
this.helpers({
questions() {
return Questions.find({categoryId: this.categoryId});
}
});
First question: How do I access this helper (questions) within it's own controller? I tried $scope.questions, this.questions and this.play.questions (play is the alias of the controller). Everything is undefined.
In my view I iterate with ng-repeat='question in play.questions' and it works fine.
Then I thought maybe helpers can't be accessed in the controller. So I tried this:
this.questions = Questions.find({categoryId: this.categoryId});
But here the problem is that I get an empty cursor. Any idea why that is?
I assume you are in your controller function and you have used
$reactive(this).attach($scope)
before you do
this.questions = Questions.find({category: this.categoryId});
? One reason your cursor is empty when not using a helper might be that your subscription is not ready by the time you set this.questions. Therefore you should make this assignment reactive by wrapping it inside a this.autorun. By doing this the cursor gets updated as soon as your client side collection is populated.
I think instead of calling your helper from within your controller you should extract a common function and use it inside the helper and whereever else you need it. The helpers are really only used to get data to the UI if I am not mistaken (<- ?).

angularjs with soundmanager, update DOM on whileloading

I'm new to Angularjs, and I'm trying to create a simple player using soundManager library.
The problem i'm facing is about updating the DOM, during sound loading/playing.
The soundManager Sound object exposes some dynamic properties like bytesLoaded or position and I'm trying to figure out how to bind them to the DOM.
I tried with something like
<span ng-bind="sound.bytesLoaded"></span>
where sound is an instance of the sound object attached to the root $scope, but it seems the DOM is updated only once in this way.
The problem might be that the sound.bytesLoaded is updated in non-angular world like, callback function of bytes loaded or some similar callback methods which is non-angular world.
To make the view update while updating the model value in non-angular world, you may need to call the $scope.$apply method from within the callback method of the SM2.
Some pseudo code:
sound.on('bytesLoaded', function(bytesLoaded){
// Imagine you have some similar kind of the callback in SM2,
// where you will be updating the sound.bytestLoaded property.
sound.bytesLoaded = bytesLoaded;
$scope.$apply(); // please make sure you call have this line
// where you are updating the bytesLoaded property.
})

Test Driving Backbone view events

I am trying to test drive a view event using Jasmine and the problem is probably best explained via code.
The view looks like:
App.testView = Backbone.View.extend({
events: { 'click .overlay': 'myEvent' },
myEvent: function(e) {
console.log('hello world')
}
The test looks something like:
describe('myEvent', function() {
it('should do something', function() {
var view = new App.testView();
view.myEvent();
// assertion will follow
});
});
The problem is that the view.myEvent method is never called (nothing logs to the console). I was trying to avoid triggering from the DOM. Has anyone had similar problems?
(Like I commented in the question, your code looks fine and should work. Your problem is not in the code you posted. If you can expand your code samples and give more info, we can take another look at it. What follows is more general advice on testing Backbone views.)
Calling the event handler function like you do is a legitimate testing strategy, but it has a couple of shortcomings.
It doesn't test that the events are wired up correctly. What you're testing is that the callback does what it's supposed to, but it doesn't test that the action is actually triggered when your user interacts with the page.
If your event handler needs to reference the event argument or the test will not work.
I prefer to test my views all the way from the event:
var view = new View().render();
view.$('.overlay').click();
expect(...).toEqual(...);
Like you said, it's generally not advisable to manipulate DOM in your tests, so this way of testing views requires that view.render does not attach anything to the DOM.
The best way to achieve this is leave the DOM manipulation to the code that's responsible for initializing the view. If you don't set an el property to the view (either in the View.extend definition or in the view constructor), Backbone will create a new, detached DOM node as view.el. This element works just like an attached node - you can manipulate its contents and trigger events on it.
So instead of...
View.extend({el: '#container'});
...or...
new View({el:'#container'});
...you should initialize your views as follows:
var view = new View();
$("#container").html(view.render().el);
Defining your views like this has multiple benefits:
Enables testing views fully without attaching them to DOM.
The views become reusable, you can create multiple instances and render them to different elements.
If your render method does some complicated DOM manipulation, it's faster to perform it on an detached node.
From a responsibility point of view you could argue that a view shouldn't know where it's placed, in the same way a model should not know what collection it should be added to. This enforces better design of view composition.
IMHO, this view rendering pattern is a general best practice, not just a testing-related special case.

Backbone boilerplate Events

What is the best way to bind events to a Backbone boilerplate application? I've been trying to bind my events directly to the models associated with my views, in my views, but it doesn't seem to be working. I see within 'namespace.js', that there is an app key that extends Backbone.Events like so:
// Keep active application instances namespaced under an app object.
app: _.extend({}, Backbone.Events)
I don't fully understand how to use it...
I was able to get things working without the boilerplate, but it does provide some very cool functionality, so I'd love to be able to use it. Thanks!
ADDED
the code I was using was with the underscore bind method like so:
this.module.bind('change', this.render);
But then, I realized that 'this.model' is returning undefined, and so this doesn't work. I really am not sure how the boilerplate wants me to reference my model from the view.
I'm not sure if it is a typo that you copied from your code or a typo you only entered here, but I believe this.module (which IS undefined) should be this.model, which you also must be sure to pass in when you instantiate your view, of course, as so:
myView = new BBView({model: myModel});
then you can say this.model.bind('change', this.render); or this.model.on('change', this.render); for the most recent version of Backbone
I frequently bind my views to change events on my models in this way.
As for extending Backbone.Events, the way I have used it is to create an independent "event aggregator" that will help connect events between different views on your page. Let's say for example you have some action on one view that needs to set off an action on another view. In this case, you can pass your event aggregator object as an option to each of your views when you instantiate them, so that they can both trigger events or bind to events on a common object (i.e. your event aggregator).
whatsUp = _.extend({}, Backbone.Events) // the aggregator
myFirstView = new FirstBBView ({whatsUp: whatsUp});
(the aggregator shows up as this.options.whatsUp inside the view)
mySecondView = new SecondBBView2 ({whatsUp: whatsUp});
inside FirstBBView:
this.options.whatsUp.bind('specialEvent', function(arg1,arg2) {
// do stuff
});
inside SecondBBView, when something important happens:
this.options.whatsUp.trigger('specialEvent', {arg1: 'some data', arg2: 'more data'});
For a great explanation, see this great article by Derick Bailey

Jquery persistent css selector equivalent to '.live()'

So today I just came across the 'live()' function that binds any future and past elements to the whatever event you choose, such as 'onclick'.
Right now I'm having to set up buttons like the following each time I load a new button via ajax ...
$('a.btn.plus').button({icons:{primary:'ui-icon-plusthick'}});
$('a.btn.pencil').button({icons:{primary:'ui-icon ui-icon-pencil'}});
$('a.btn.bigx').button({icons:{primary:'ui-icon ui-icon-closethick'}});
So, instead of calling these lines each time I use ajax to add a new button, is there a similar way to tell JQuery to setup my buttons ANYTIME I add new ones?
Thanks for any help!
Mmh not really. But there is the function .ajaxSuccess() which is triggered whenever an Ajax call is successful. So you could do:
$('body').ajaxSuccess(function() {
$('a.btn.plus').button({icons:{primary:'ui-icon-plusthick'}});
$('a.btn.pencil').button({icons:{primary:'ui-icon ui-icon-pencil'}});
$('a.btn.bigx').button({icons:{primary:'ui-icon ui-icon-closethick'}});
});
But this will run on any links with the classes, not only on the new ones. But if you append them on a time (i.e. not multiple a.btn.plus at once) you might be able to use the :last selector (a.btn.plus:last).
You can also create a function and just that from your callback functions:
function links() {
$('a.btn.plus').button({icons:{primary:'ui-icon-plusthick'}});
$('a.btn.pencil').button({icons:{primary:'ui-icon ui-icon-pencil'}});
$('a.btn.bigx').button({icons:{primary:'ui-icon ui-icon-closethick'}});
}
and in the Ajax call:
$.ajax({
//...
success: function(msg){
links();
}
});
This way you can pass the parent element to the function in order to find the link only inside this element (so the code would only work on the new links).
A last option would be generate a custom event but in the end this would be similar to just doing a function call in your case so you gain not much.
You can use delegate in your success function too
$("body").delegate("a.btn", "hover", function(){
$(this).toggleClass("hover");
});
There is a Jquery Plugin called livequery which covers your requirements.
I like to think of this plugin as Jquery .live() but without the need for an event ('click') etc.
You can find more info here//
Jquery - Live Query Plugin

Resources