简体   繁体   中英

Accessing a method on a Backbone.js view inside of loop

I'm working on an app that has an ItemListView that contains a number of ItemView elements. In my ItemListView , I'm using the jQuery .each() method to loop through the collection of items and render them as list elements.

I've got all the pieces in place except for the actual attaching of the li elements to the containing ul . The sticking point is getting access to the ItemListView.appendItem method from inside of my .each() loop. I've tried using this.appendItem and self.appendItem , but inside the loop this is the item and self is the window object.

Here's what I have right now:

ItemListView = Backbone.View.extend({
    el: '#item-rows',
    initialize: function () {
        this.collection = new Items();
        this.render();
    },
    render: function () {
        $.each(this.collection.models, function (i, item) {
            var itemview = new ItemView( { model: item });
            this.appendItem(itemview); // this refers to the item, so appendItem is undefined
        });
    },
    appendItem: function (itemView) {
        $(this.el).append(itemView.render().el);
    }
});

var itemlistview = new ItemListView;

I'm pretty sure that the context issue is the only problem, as I've examined the other pieces of the this by outputting them to the console and they look fine.

What am I missing?

A more Backbone-y way to do this would be to use the collection's each , provided by underscore.js:

render: function() {
  this.collection.each( function( item, index ) {
    var itemView = new ItemView( { model:item } );
    this.appendItem( itemView );
  }, this );
  return this;
}

Notes:

  • notice the second param to each which take a reference to bind the function to
  • the each takes the element first and the index second
  • render should generally return this for chaining purposes (as mentioned in the docs ), I don't think your appendItem function will work as you expect without this part

Yeah, it's a pretty simple fix. You just gotta refer to the this in the outer context.

render: function () {
    var somereftothis = this;
    $.each(this.collection.models, function (i, item) {
        var itemview = new ItemView( { model: item });
        somereftothis.appendItem(itemview); // this refers to the item, so appendItem is undefined
    });
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM