2014-04-28 54 views
0

我在带有主干和把手的页面上呈现两个模型。我试图将两个模型连接在一起,但concat()函数返回error:Undefined is not a function未定义不是带concat的函数

这是我的渲染功能:

render: function (eventName) { 
    var twitter=this.collection.models[0].toJSON(); 
    var instagram=this.collection.models[1].toJSON(); 
    var conc=twitter.concat(instagram); <--LINE ERROR  
    $(this.el).html(this.template(conc)); 
    return this; 
}, 
+0

是否在twitter中有任何数据? – Pete

+0

是的,它...... –

+0

什么是行?如果您有麻烦,请使用**行号码发布错误**并标记相关行!尝试'console.log(typeof(twitter),twitter);' –

回答

1

从一些评论到原帖this.collection.models[0].toJSON()返回JSON的字符串表示,显然用于发射。

为了使其达到可行状态,需要将它们转换为实际的JavaScript对象。

JSON.parse(this.collection.models[0].toJSON()) 

如果返回一个对象,那么你可以使用jQuery.extend()来连接的对象。

如果它返回一个数组,那么你可以使用扩展方法.concat()

如果this.collection.models[0]只是一个对象,然后用它们jQuery.extend(),没必要和.toJSON()如艾略特指出,但是,如果是喜欢knockoutjs任何地方的对象在中,toJSON可能是要走的路观测,获得纯粹的对象。

var finalObj = {}; 
var twitter = this.collection.models[0]; 
var instagram = this.collection.models[1]; 
$.extend(finalObj, twitter, instagram); 
+0

Backbone模型的['toJSON'](http://backbonejs.org/#Model-toJSON)返回一个Object,而不是String。这是['JSON.stringify'期望的行为](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON_behavior),因此可怜的名字是方法。 'models [0]'应该是一个Backbone模型实例,'$ .extend'不会对这样的事情做任何有用的事情。 –