Getting value of parent model with Backbone.js

≯℡__Kan透↙ 提交于 2019-12-12 02:08:53

问题


I have a backbone application with the following architecture:

A PageGroupCollection is a collection of PageGroupModels.

A PageGroupModel has a PageCollection as one of it's attributes.

A PageCollection is a collection of PageModels


PageGroupModel has a permalink attribute

PageModel has a permalink attribute.

I need a function within PageModel that returns a permalink that includes both the permalink of PageModel thats PageCollection attribute contains PageGroupModel and also its own permalink attribute.

Something like the following:

getFullPermalink: function () {

    var parentPermanlink = this.owningCollection.modelCollectionIsAnAttributeOf.get('permalink');

    return parentPermalink + "/" + this.get('permalink');
}

Update: Worked by adding the following:

var pageGroup = pageGroupCollection.findWhere({ 'pageCollection': this.collection });
var pageGroupPermalink = pageGroup.get('permalink');
return pageGroupPermalink + "/" + this.get('permalink');

回答1:


Backbone isn't really made to work with nested models (Backbone-Relational may be interesting). But if you have access to the entry point of your tree (in your example, to the instance of PageGroupCollection), you can do that:

var parent = myPageGroupCollection.findWhere({pageCollection: myPageModel.collection});

With myPageModel being your child model and pageCollection the collection attribute of the PageGroupModel.

Supposing you also don't mess with the collection attribute of your models (if your model is in several collections for example).



来源:https://stackoverflow.com/questions/17381113/getting-value-of-parent-model-with-backbone-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!