I have a code in Javascript as :
_.each(this.collection.models, function (student) {
$(this.el).append(new StudCloneItemView({ model: student }).el);
}, this);
While I am writing This in coffescript as
_.each this.collection.models , (student) =>
$(@el).append new Item ({ model:student }).el
which generates
_.each(this.collection.models, function(student) {
return $(_this.el).append(new Item({
model: student
}.el));
});
Which isn’t desirable as per my requirement . The last segment of “this” element has been missing into the generated javascript . Its very important.
How would I generate The javascript as mentioned on top using the coffeescript I mentioned for _.each ????
Is there anyway to do that ?? Or am I missing any syntax ?
Your JavaScript:
and what your
=>CoffeeScript produces:are functionally equivalent. You don’t need the context argument to
_.eachsince the=>generates an alias forthis(called_this) that is used inside the callback.As an aside, Backbone collections have various Underscore methods mixed in so you don’t have to say
_.each(@collection.models, ...), you can useeachdirectly on the collection:I’ve also switched to the pre-built
$elthat your view already has, there’s no need to build a new jQuery object on each iteration.