Something like jQuery.ready(fn) for Backbone collections and models - events

I have a preloaded object graph of Backbone collections and models. To initialize my UI I need to make sure the collections are loaded, and then pull some item from them by ID using get(). I want to have a method that accepts a callback which is either called immediately if the collection is loaded, or gets delayed until the collection is loaded.
So far I have the following abomination of a mixin:
window.BackboneReady =
onReady: (cb)->
if #loaded_
console.log "Calling onReady immediately"
cb(#)
else
console.log "Scheduling onReady for later"
#once 'sync', =>
console.log "onReady fired in callback"
#loaded_ = true
cb(#)
however, it only works sometimes (I see the message "Scheduling onReady for later" but my event handler is never executed). Rant: it looks Backbone doesn't even have a basic signal variable to tell me whether the object is synced or not, which seems completely absurd.
What would be the sane way to accomplish this? I don't want to call fetch() every time I want to get() an object from the collection for my UI since this defeats the purpose of holding a preloaded object graph in the first place.

You can try this in your collection to use promises and solve your challenge
initialize: function(){
this.on("request", function(collection, xhr, options){
this.ready = xhr;
});
}
Then you can do
$.when(myCollection.ready).done(function(){
// do things to the collection that is ready
console.log(myCollection.get(5));
});
Or in your collection:
getIfLoaded: function(id){
if(this.ready.state === "resolved"){
return this.get(id);
}
else{
return null;
}
}
For more info on deferred and promises, take a look at http://davidsulc.com/blog/2013/04/01/using-jquery-promises-to-render-backbone-views-after-fetching-data/ and http://davidsulc.com/blog/2013/04/02/rendering-a-view-after-multiple-async-functions-return-using-promises/

Related

Ember afterRender component / non-async AJAX

Imagine a component that renders an HTML table. The data from the table comes from remote JSON.
Another part of the component relies on the HTML table being fully rendered (with the JSON data).
On the component's init event, I retrieve the JSON and set the data that the component will use to render the table.
I can't use an afterRender hook to further process the table, because when the afterRender is fired, the table exists but without the JSON data.
I noticed that an afterRender hook outside the component works (the table is fully rendered), but then I'd break the encapsulation by running code that belongs inside the component.
I could maybe get the JSON synchronously, or perhaps a promise within a promise? How would I do the latter? What I mean is on the component's init hook, how do I create a promise which returns only when the promise inside it is returned?
Or how can I approach this the Ember way?
You can definitely chain the hell out of your promises.
var items = [];
this.set('items', items);
$.getJSON('/colors').then(function(results){
results.forEach(function(item){
item.color +=" is pretty";
});
return results;
}).then(function(prettyResults){
prettyResults.forEach(function(item){
items.pushObject(item);
});
});
http://emberjs.jsbin.com/OxIDiVU/724/edit
Super deep convoluted promises
new Ember.RSVP.Promise(function(resolve){
resolve($.getJSON('/colors'));
}).then(function(results){ // this isn't hit til the json is returned
results.forEach(function(item){
item.color +=" is pretty";
});
return new Ember.RSVP.Promise(function(resolve){
Ember.run.later(function(){
resolve(results);
}, 4000);
});
}).then(function(prettyResults){ // this isn't hit til the 4 second resolve is done
prettyResults.forEach(function(item){
items.pushObject(item);
});
});
http://emberjs.jsbin.com/OxIDiVU/725/edit

BackboneJS .ajaxStart() and .ajaxStop() while fetching collection

I have a BackboneJS App where I fetch a bunch of collections. Now I want to apply some sort of loader to indicate that the collection is loading and the user gets to know that something is happening. So I want to use the .ajaxStart() and .ajaxStop()-method. So I was thinking about something like this:
this.artistsCollection.fetch(
$(document).ajaxStart(function () {
console.log('ajax start');
$('.someDiv').addClass('TEST');
}),
$(document).ajaxStop(function () {
console.log('ajax stop');
// stop doing stuff
})
);
Issue is that first time I trigger the .fetch() my console says ajax stop and the class is not applied!?!? Second time I trigger the .fetch() it works like it should and the class gets applied. Does anyone know whats the issue?
Please help anyone?
You're passing the returned result of adding the two event handlers with jQuery as parameters to the Collection fetch method. The Backbone Collection fetch method receives an options object which can include a success callback (see documentation).
I think if you move the listeners out of the method call it should work as you expect:
// Global AJAX listeners
$(document).ajaxStart(function () {
console.log('ajax start');
// do stuff
});
$(document).ajaxStop(function () {
console.log('ajax stop');
// stop doing stuff
});
this.artistsCollection.fetch();

Ajax request in Backbone View render function

I want to pass an extra variable (the userid) with before rendering my backbone view. I am getting the the extra variable with a ajax request but because is asynchronous I think my page is being rendered before I get the variable. For simplicity lets say I have this in my backbone view :
PostsApp.Views.Post = Backbone.View.extend({
template: _.template($('#post-template').html()),
render: function(){
var newObject = this.model.toJSON();
$.ajax({
url:"/user",
success:function(result){
newObject.twittername = result.name; ;
}
});
this.$el.html(this.template(newObject));
}
});
I guess I can put this.$el.html(this.template(newObject)); in the callback but than 'this'refers to something else.. Can anyone think of a work around for this?
Or is it completely very bad to send such a request in the render function..
You are correct in your assumption. It will not render correctly.
The simple fix
Just like the more general case, you can perform the actual rendering inside the success callback.
render: function(){
var newObject = this.model.toJSON();
var that = this; // to fix that `this` refers to in the callback
$.ajax({
url:"/user",
success:function(result){
newObject.twittername = result.name; ;
that.$el.html(that.template(newObject));
}
});
}
The better fix
What I'd do is:
Have the twitter name as a part of the model
fetch it from the model (maybe even with a restful .fetch
listen to change events in the view, and call render on such events.
This is because the view should not be responsible for changing model data in Backbone. It's mixing "business logic" with presentation and it can get ugly pretty fast.
[I think this example 2 from Addy Osmani's "Backbone Fundamentals" should give you a general idea on how this sort of structure is laid out.

jQuery Delegate not binding like I want it to

Using jQuery 1.7
I'm having trouble binding a Click event to some dynamically loaded content.
I've looked around, tried .live, .delegate and .on, and I just can't get it to work.
This is my code:
$(".fileexplorer_folderdlg").delegate(".delete", "click", function () {
console.log("Hello world!");
});
The thing is, .fileexplorer_folderdlg is dynamically loaded. If I use .fileexplorer (not dynamically loaded), it works, but I have more elements with the .delete class that I do not wish to bind to (and neither element classes can be renamed or changed for various reasons).
I also tried using .fileexplorer_folderdlg .delete as the .delegate selector, didnt work either!
Of course I could just add another unique class to the elements I wish to bind to, but this really should work, right?
I believe this would work:
$(document).on('click', '.delete', function() {
if ($(this).closest('.fileexplorer_folderdlg').length) {
console.log('hello, world!');
}
});
or even just:
$(document).on('click', '.fileexplorer_folderdlg .delete', function() {
console.log('hello, world!');
});
As you've found, you can't bind on .fileexplorer_folderdlg because it's dynamic. You therefore need to bind on some static element that will contain that element at some point in the future.
Instead, this binds on the document (but will unfortunately fire for every single click on the document thereafter).
EDIT by Jeff
Although the code above did not work, modifying it a bit did the job, although not the most desirable solution.
$(document).on('click', '.delete', function () {
if($(this).closest(".fileexplorer") != null)
console.log("Thanks for your help!");
});
It works, but this event is fired for all other .delete classes, of which there are many. What I do not understand though, is why using .fileexplorer_folderdlg .delete did not work!

Event removal in Mootools, and syntax of event addition

So I have been adding my events thusly:
element.addEvent('click', function() {
alert('foobar');
});
However, when attempting to remove said event, this syntactically identical code (with "add" switched to "remove") does not work.
element.removeEvent('click', function() {
alert('foobar');
});
I assume this is because the two functions defined are not referenced the same, so the event is not technically removed. Alright, so I redefine the event addition and removal:
element.addEvent('click', alert('foobar'));
element.removeEvent('click', alert('foobar'));
Which works great, except now when the page loads, the click event is fired even before it's clicked!
The function is removed, though, which is great......
update: when you do .addEvent('type', function(){ }) and .removeEvent('type', function(){ }), even though the functions may have the same 'signatures', they are two separte anonymous functions, assigned on the fly. function 1 is !== to function 2 - hence there is no match when MooTools tries to remove it.
to be able to remove an exact handler, o:
function handler(){ ... }
el.addEvent('click', handler);
// .. later
el.removeEvent('click', handler);
Internally, events are actually a map of keys to functions in element storage. have a look at this fiddle i did a while back for another SO question - http://www.jsfiddle.net/mVJDr/
it will check to see how many events are stacked up for a particular event type on any given element (or all events).
similarly, removeEvent looks for a match in the events storage - have a look on http://jsfiddle.net/dimitar/wLuY3/1/. hence, using named functions like Nikolaus suggested allows you to remove them easily as it provides a match.
also, you can remove events via element.removeEvents("click") for all click events.
your page now alerts because you pass on alert as the function as well as execute it with the params 'foobar'. METHOD followed by () in javascript means RUN THE METHOD PRECEDING IT IMMEDIATELY, NOT LATER. when you bind functions to events, you pass the reference (the method name) only.
to avoid using an anonymous function and to pass argument,s you can do something like:
document.id('foobar').addEvent('click', alert.bind(this, 'foo'));
as bind raps it for you, but removing this will be even more complicated.
as for event delegation, it's:
parentEl.addEvents({
"click:relay(a.linkout)": function(e, el) {
},
"mouseover:relay(li.menu)": function(e, el) {
}
});
more on that here http://mootools.net/docs/more/Element/Element.Delegation#Element:removeEvent
keep in mind it's not great / very stable. works fine for click stuff, mouseenter is not to be used delegated, just mouseover - which means IE can fire mouseout when it should not. the way i understand it, it's coming improved in mootools 2.0
edit updating to show an example of bound and unbound method within a class pattern in mootools
http://www.jsfiddle.net/wmhgw/
var foo = new Class({
message: "hi",
toElement: function() {
return this.element = new Element("a", {
href: "http://www.google.com",
text: "google",
events: {
"click": this.bar.bind(this), // bind it
"mouseenter": this.bar // unbound -> this.element becomes this
}
});
},
bar: function(event) {
event.stop();
// hi when bound to class instance (this.message will exist)
// 'undefined' otherwise.
console.log(this.message || "undefined");
}
});
document.id(new foo()).inject(document.body);
the mouseenter here will be unbound where this will refer to the default scope (i.e the element that triggered the event - the a href). when bound, you can get the element via event.target instead - the event object is always passed on to the function as a parameter.
btw, this is a slightly less familiar use of class and element relation but it serves my purposes here to illustrate binding in the context of classes.
assig the function to a variable and use the same reference to add and remove the event.
if you use an anonymous function you will get to different references
var test = function(){ alert('test: ' + this.id); }
$('element').addEvent('click', test);
...
$('element').removeEvent('click', test);
addEvent : Attaches an event listener to a DOM element.
Example -
$('myElement').addEvent('click', function(){
alert('clicked!');
});
removeEvent : Works as Element.addEvent, but instead removes the specified event listener.
Example -
var destroy = function(){ alert('Boom: ' + this.id); } // this refers to the Element.
$('myElement').addEvent('click', destroy);
//later...
$('myElement').removeEvent('click', destroy);
This means when you add an event with a eventhandler not an anonymous function if you than remove the event than it will be removed.

Resources