骨干对待模型像收藏 [英] Backbone treat model like collection

查看:74
本文介绍了骨干对待模型像收藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Collections实际上是模型,因此具有属性等,如本例所示

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

我将Collection替换为Model并传递给视图.我得到了this.model.each of undefined.

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

推荐答案

因为馆藏实际上是一个模型

Since Collections is actually a model

不.这是错误的假设.集合不是模型,这就是为什么您的代码无法正常工作的原因.

No. This is wrong assumption. Collection is not a model which is why your code doesn't work.

模型没有每个方法,您的代码将引发以下错误:

Model does not have an each method and your code throws following error:

Uncaught TypeError: this.model.each is not a function(…)

,不要遵循对模型属性进行迭代并打印其名称的其他答案,这没有任何意义.因为模型应该代表一个实体,就像一个人.它只有一个包含名称的属性,没有必要遍历模型属性以访问其中之一,您可以使用get()方法直接访问其属性,而无需进行迭代.

and don't follow the other answer that iterates over model properties and prints it's name, it doesn't make sense. Because model is supposed to represent an entity, like a person. It'll only have one property containing name, there's no point in iterating over model properties to access one of them, you can directly access it's attributes with get() method without having to iterate.

这篇关于骨干对待模型像收藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆