Backbone.js从不同的资源获取属性以进行模型输入

时间:2013-07-03 16:03:56

标签: javascript rest backbone.js

我尝试使用来自2个不同Rest Service的值生成Backbone Collection。我得到了1个休息服务,它给我一个包含General Propertys的列表,例如:

{["id":"31", "folder":"fid3223"]}
{["id":"12", "folder":"fid2323"]}

我在一个集合中获取它们,现在我希望每个模型都能获得他的属性,我只能通过他的身份从另一个休息Ressource获得。我想在这个集合中安全地保护他们:

{["id":"31", "folder":"fid3223", propertys["prop1":"value1","prop2":"value2","prop3":"value3"]]}
{["id":"12", "folder":"fid2323",propertys["prop1":"value1","prop2":"value2","prop3":"value3"]]}

使用骨干网是一种简单的方法吗?

2 个答案:

答案 0 :(得分:1)

我认为您正在寻找合并Model的属性。

从服务器获取数据后,您可以执行以下操作:

var models = [ {..}, {..} ]; // Two javascript objects holding the attributes, let's assume these are from the second fetch
collection.set(models, { merge: true }); // Here Backbone will look for existing objects in that collection and merge their attributes

你如何获取数据是另一回事 如果它使用Backbone提供的fetch()方法,并且新属性位于propertys内,则应覆盖集合的parse()方法...请参阅Backbone的文档。

答案 1 :(得分:0)

首先,我认为从Rest Service 1获取的“模型”应如下所示:

{"id":"31","folder":"fid3223"}
{"id":"32","folder":"fid2323"}

一个对象代表一个列表项吗?

您的合并集合应如下所示:

[{"id":"31","folder":"fid3223","propertys":{"prop1":"value1","prop2":"value2","prop3":"value3"}}

您希望将这两个Rest服务数据合并到一个集合中。当您的数据设置了唯一的id属性时,Backbone fetch方法将执行“智能”提取。所以你可以将Rest1服务提取到集合中并动态地将其url属性更改为Rest2 url然后再次获取。将合并相同的id列表数据。

简单示例:

<强>型号:

var List = Backbone.Model.extend({

});

<强>收集:

var Lists = Backbone.Collection.extend({
    model: List,
    url:"ur/url/to/rest1"
});

var lists = new Lists();

查看:(checkItem函数可以帮助您查看您收集的模型发生了什么)

var ListView = Backbone.View.extend({
    el: "#list-view",
    initialize: function(){
        this.listenTo(lists,"add",this.checkItem);
        this.listenTo(lists,"change",this.checkItem);
    },
    checkItem: function(model){
        console.dir(model);
});

var listView = new ListView();

$("#basic-btn").click(function(){
    lists.fetch();
});

$("#property-btn").click(function(){
    lists.url = "ur/url/to/rest2";
    lists.fetch();
});

<强> HTML:

<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/jquery-easing-1.3.js"></script>
<script src="js/bootstrap.min.js"></script>
<!--backbone-->
<script type="text/javascript" src="js/backbone/underscore.js"></script>
<script type="text/javascript" src="js/backbone/backbone.js"></script>

<script type="text/javascript" src="js/test.js"></script>
</head>
<body>
<button id="basic-btn">load basic</button>
<button id="property-btn">load property</button>
<ul id="list-view">
</ul>
</body>
</html>

首先我点击“basic-btn”并得到这个结果:

enter image description here

然后我点击“property-btn”,属性将合并到现有列表项中:

enter image description here

希望这对你有所帮助。