【问题标题】:Where are my Models after fetching a nested json backbone collection获取嵌套的 json 主干集合后我的模型在哪里
【发布时间】:2014-08-23 20:58:47
【问题描述】:

Total Backbone js noob,我试图了解我正在使用的返回 json 的 api 是否不适合骨干网(或不适合任何东西),或者我只是不知道如何收集和模型在 Backbone 中已经足够工作了。

我知道集合的 fetch 正确返回了 json,这可能是我处理响应的方式。令人困惑的是,我真的不知道正确获取的集合想要什么以及获取后模型的存储位置。看来我想要的模型存储为集合模型属性中的对象......对吗?

另外,我想作为第二个问题,我的集合似乎或多或少没有解析每个模型,而是只创建一个包含我的模型集合的模型。我不知道怎么做,但我希望反过来,我的模型的一个集合。有什么指点吗?

让我列出一些代码,然后我将提供一个 json 响应示例(我的示例将只包含 3 个对象),以及一个获取集合的控制台日志。非常感谢您的帮助和任何建议。谢谢!

我的引导文件:

//statusApp.js 

(function($){

    var statusGroup = new app.StatusCollection();

    var deferred = statusGroup.fetch({
        data: {
            action: "get_my_status_collection"
        }
    });

    /* wait till fetch is complete */
    $.when(deferred).then(function(){

        console.log('returned collection', statusGroup);

        var statusGroupView = new app.allStatusView({ collection: statusGroup});

        $(".service-statuses").html(statusGroupView.render().el);

        var statusRouter = new app.Router();

        Backbone.history.start();
    });

})(jQuery);

以下是收到的响应示例,显示了它从服务器附带的所有嵌套节点。你会在我的集合的解析函数中看到只返回“对象”节点,我不需要其余的(它可能不适用于这些顶级节点?)

{
  "component":{
    "status":"2",
    "count":"3",
    "objects":{
        "80":{
            "name":"Calendar",
            "parent":"0",
            "status":"3",
            "description":"Exchange Calendar",
            "comment":""
        },
        "220":{
            "name":"Solution Services",
            "parent":"0",
            "status":"3",
            "description":"",
            "comment":""
        },
        "2":{
            "name":"Tech Portal",
            "parent":"0",
            "status":"2",
            "description":"",
            "comment":""
        },
    }
  },
"in_maint":[],
"success":true
}

这是从集合获取中返回的 json 的控制台日志:

statusGroup 
d {length: 1, models: (...), _byId: Object, url: (...), trigger: function…}
    [object Object]: undefined
    get [object Object]: function () {
    set [object Object]: function (newval) {
    __backboneDebugger__appComponentInfo: window.__backboneAgent.AppComponentInfo
    __backboneDebugger__isInstancePatched: true
    _byId: Object
    initialize: function () {
    length: 1
    models: Array[1]
    0: d
        __backboneDebugger__appComponentInfo: window.__backboneAgent.AppComponentInfo
        __backboneDebugger__isInstancePatched: true
        _changing: false
        _events: Object
        _pending: false
        _previousAttributes: Object
        attributes: Object
            2: Object
                comment: ""
                description: ""
                name: "Tech Portal"
                parent: "0"
                status: "3"
            get 2: function () {
            set 2: function (newval) {
            80: Object
                comment: ""
                description: "Exchange Calendar"
                name: "Calendar"
                parent: "0"
                status: "2"
            get 80: function () {
            set 80: function (newval) {
            220: Object
                comment: ""
                description: ""
                name: "Solution Services"
                parent: "0"
                status: "3"
            get 220: function () {
            set 220: function (newval) {
            watchers: Object
            __proto__: Object
        get attributes: function () {
        set attributes: function (newval) {
        changed: Object
        cid: (...)
        get cid: function () {
        set cid: function (newval) {
        collection: (...)
        get collection: function () {
        set collection: function (newval) {
        id: (...)
        get id: function () {
        set id: function (newval) {
        initialize: (...)
        sync: function (){return b.sync.apply(this,arguments)}
        trigger: function (a){if(!this._events)return this;var b=g.call(arguments,1);if(!j(this,"trigger",a,b))return this;var c=this._events[a],d=this._events.all;return c&&k(c,b),d&&k(d,arguments),this}
        urlRoot: (...)
        get urlRoot: function () {
        set urlRoot: function (newval) {
        watchers: Object
        __proto__: f
    get 0: function () {
    set 0: function (newval) {
    length: 1
    pop: function () {
    push: function () {
    reverse: function () {
    shift: function () {
    slice: function () {
    sort: function () {
    unshift: function () {
    watchers: Object
    __proto__: Array[0]
get models: function () {
set models: function (newval) {
sync: function (){return b.sync.apply(this,arguments)}
trigger: function (a){if(!this._events)return this;var b=g.call(arguments,1);if(!j(this,"trigger",a,b))return this;var c=this._events[a],d=this._events.all;return c&&k(c,b),d&&k(d,arguments),this}
url: (...)
get url: function () {
set url: function (newval) {
watchers: Object
__proto__: f

我的收藏:

// allStatus.js

var app = app || {};

// A group (array) of Status models
app.StatusCollection = Backbone.Collection.extend({

    model: app.singleStatus,
    url: "/remote/api/status_json",
    parse: function(response){

        //return only the nested objects that will be our models
        return response.component.objects;

    }

 });

我的收藏视图:

// allStatusView.js

var $ = jQuery.noConflict();
var app = app || {};

app.allStatusView = Backbone.View.extend({

    tagName: "ul",

    render: function() {

        this.collection.each(this.addStatus, this);
        return this;
    },

    addStatus: function(status) {

        var statusView = new app.singleStatusView({ model: status });
        this.$el.append(statusView.render().el);
    }

});

我的单一观点:

// singleStatusView.js

var $ = jQuery.noConflict();
var app = app || {};

app.singleStatusView = Backbone.View.extend({

    tagName: "li",
    className: "service-status",

    template: _.template( $("#statusElement").html() ),

    render: function() {

        var statusTemplate = this.template(this.model.toJSON());
        this.$el.html(statusTemplate);
        return this;
    }

});

【问题讨论】:

  • 由于您的响应是一个对象,而不是一个集合(列表/数组),您需要覆盖集合的 parse 方法以获取集合所需的格式。您实际需要访问哪些数据?
  • 感谢您的回复,我没有意识到集合不能是一个对象,嗯。我正在覆盖集合的解析(请参阅上面的集合代码块)以获取返回响应的“对象”节点。 “对象”节点是我正在考虑我的模型的每个对象所在的位置。我基本上需要访问每个对象的“名称”、“状态”、“父”和“描述”值。
  • 我会写一个我认为能满足你需要的 parse 版本。

标签: json backbone.js nested fetch backbone.js-collections


【解决方案1】:

以下是您如何将“对象”转换为您的收藏所需的格式:

app.StatusCollection = Backbone.Collection.extend({

    model: app.singleStatus,
    url: "/remote/api/status_json",
    parse: function (response){

        var obj = response.component.objects;

        // add the additional properties that won't be in your "models"
        // to the collection object directly if you want them

        this.status = response.component.status;
        this.count = response.component.count;

        // convert the "objects" object to an array and return
        // the resulting array

        return _.map(obj, function (value, key) {
          return obj[key];
        });
    }
});

我将“组件”中的其他属性直接添加到集合对象中,但这不是必需的——它们只有在您需要保留这些属性时才会出现。您可以对末尾不属于“组件”的其他属性执行相同的操作。

【讨论】:

  • 做到了,非常感谢!我可能在这里还有其他一些问题,但它现在实际上正在工作。还包括其他属性的荣誉,我也需要这些。谢谢! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多