Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - Backbone treat model like collection

Since Collections is actually a model, it has attributes and so on, like in this example

var Images = Backbone.Collection.extend({
  url: 'https://api.myjson.com/bins/4v2d8'
});

var View = Backbone.View.extend({
  el: $('.images'), 

  initialize: function(){
    this.listenTo(this.collection, 'sync', this.render, this); // what is this keyword as the last param here?
  },

  render: function(){

    this.collection.each(function(model){
      this.$el.append($('<p>'+model.get('name')+'</>' ));
    }, this);

  }
});

$(function(){

  var images = new View({ collection: new Images() });

  images.collection.fetch();

});

http://jsbin.com/gohedeguto/edit?html,js,output

But why this one doesn't work?

http://jsbin.com/seyoyeqeku/edit?html,js,output

I replaced Collection with Model and passed to the View. I got this.model.each of undefined.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

While T-J is right, he doesn't elaborate on why.

A Backbone model has lots of functions to manage an attributes hash, and is often referenced by an id.

A Backbone collection is an array of Backbone model instances. It has some similar and lots of different functions to manage its models array property which is where the model instances are stored.

Some of these functions are proxies to Underscore.js functions.

Model's Underscore methods

  • keys
  • values
  • pairs
  • invert
  • pick
  • omit
  • chain
  • isEmpty

Collection's Underscore methods

46 in total at the moment, see the list.


collection.each(iteratee, [context])

is a proxy to _.each(collection.models, iteratee, [context]).

Backbone's Model do not have a each function because it doesn't really make sense and there are better ways to loop through the attributes of a model.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...