1

我正在学习 Backbone.js。我喜欢我所看到的,但对我来说有些不清楚......处理页面上已经存在的数据的最佳方法是什么。最好是遍历所有这些并为每个创建一个模型。

$('element').each(function() {
     var model = new Model();
     collection.add(model);
});

或者我应该加载页面,然后从那里获取数据并处理它。

或者,有没有更好的方法来做到这一点,我错过了什么?

编辑

如果服务器端我循环遍历我的数据以使用页面引导它

服务器端

<div>
    <p>{{ model.someInformation }}</p>
</div>

我应该直接实例化一个新模型吗?

<script>
    Backbone.Model.extend({
        var model = new Model();
    });
</script>

我在引导程序http://backbonejs.org/#FAQ-bootstrap上阅读了有关集合重置的信息,但似乎有些东西我没有得到...我想我需要模型来添加到集合中,如果我没有的话我的模型在某个地方实例化reset了集合的用途......我在这里有点迷失了。

编辑 2

我已经能够使我的应用程序工作在执行以下操作:

$('#active-cards .card').each(function(i) {
     window['card' + i] = new Card(),
         window['cardView' + i] = new CardView({ el: $(this) });
         id = $(this).attr('id'),
         name = $(this).find('input[name="name"]').val(),
         client =  $(this).find('input[name="client"]').val(),
         field =  $(this).find('input[name="field"]').val();
     window['card' + i].set({ id: id, name: name, client: client, field: field });
     cards.add(window['card' + i]);
});

在此之后我可以通过做找到模型

var id = this.$el.attr('id');
var card = cards.get(id);
4

2 回答 2

1

不,您通常不会那样做。看起来您正在寻找在页面加载时填充集合。主干文档对此有一,称为引导。

编辑以回答评论
这可能是一个奇怪的概念,但您不需要在添加到集合之前实例化模型。根据重置文档:

使用 reset 将集合替换为新的模型列表(或属性哈希)

因此,您可以使用 Collections 指定model属性,然后简单地添加一个对象字面量数组。例如:

UserCollection = Backbone.Collection.extend({
   model: User
});
myUserCollection = new UserCollection();
myUserCollection.reset([
   {
      name: "Bob",
      age: 25
   }, {
      name: "Foo",
      age: 26
   }
]);

myUserCollection现在将包含 2 个User模型。

第二次编辑
我仍然认为您不太了解这个概念。这就是我认为你想要实现的目标:http: //jsfiddle.net/67E6t/

于 2013-03-23T15:57:24.513 回答
0

因此,如果您想将初始模型引导到集合中,您希望直接将初始模型从服务器端放入集合中。

<script>
  var myCol = new Backbone.Collection;
  accounts.reset(models_prepared_in_server>); //you utilize your server side to replace the models_prepared_in_server with your actual data.
</script>

因此,当页面传输到客户端时,您的代码可能如下所示(例如):

<script>
  var myCol = new Backbone.Collection;
  myCol.reset([
     { name: model1,
       some_prop: prop_value;
     },
     { name: model2,
       some_prop: prop_value2;
     }
  ]);
</script>

因此,在您的浏览器执行脚本后,其中myCol会充满您的模型。

于 2013-03-24T14:55:40.877 回答