0

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 ?

0

2 Answers 2

1

Your JavaScript:

_.each(this.collection.models, function (student) {
    $(this.el).append(new StudCloneItemView({ model: student }).el);
}, this);

and what your => CoffeeScript produces:

var _this = this; // This is somewhere above your _.each in the generated JS
_.each(this.collection.models, function(student) {
    return $(_this.el).append(new Item({
        model: student
    }.el));
});

are functionally equivalent. You don't need the context argument to _.each since the => generates an alias for this (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 use each directly on the collection:

@collection.each (student) =>
    @$el.append(new StudCloneItemView(model: student).el)

I've also switched to the pre-built $el that your view already has, there's no need to build a new jQuery object on each iteration.

Sign up to request clarification or add additional context in comments.

1 Comment

yes I realised tht after your post . That was really helpful how underscore and coffeescript are mixed
1

like this:

_.each @collection.models, ((student) ->
  $(@el).append new StudCloneItemView(model: student).el
), this

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.