Javascript骨干;模型不同于集合

Javascript backbone; Model differs from collection?

本文关键字:不同于 集合 模型 骨干 Javascript      更新时间:2023-09-26

相对较新的javascript和骨干。当我从一个集合中填充模型时,它工作得很好。但是当我试图获取单个模型元素时,我得到的格式与我的模型不匹配。我该怎么纠正呢?

当在url/task执行GET操作时,我得到以下JSON,并且我能够填充集合:

{
  "tasks": [
    {
      "id": 8361261004,
      "task": "test 1"
    },
    {
      "id": 3916252773,
      "task": "jhgjhg"
    },
    {
      "id": 1390322898,
      "task": "erterte"
    }
  ]
}

当我对单个模型元素执行fetch时,我得到以下格式,它不适合模型:

{
  "task": {
    "id": 8361261004,
    "task": "test 1"
  }
}

所以我试着用:

解析模型
'parse': function( apiResponse ){
    return apiResponse.task;
}

但是当我这样做时,集合不再匹配…

怎么了?

代码如下:

$.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        var ref = this.name;
        if(o[ref] !==undefined) {
            if(!o[ref].push) {
                o[ref] = [o[this.name]];
            }
            o[ref].push(this.value || '');
        }
        else {
            o[ref] = this.value || '';
        }
    });
    return o;
};
var Task = Backbone.Model.extend({
    'urlRoot': 'http://localhost:5000/tasks',
    'defaults': {
        id: null,
        task: 'default'
    }
});
var Tasks = Backbone.Collection.extend({
    'url': 'http://localhost:5000/tasks',
    'model': Task,
    'initialize': function(){
        //alert("Welcome to this world");
    },
    'parse': function( apiResponse ){
        return apiResponse.tasks;
    }
});
var TaskListView = Backbone.View.extend({
    'el': '.page',
    'template': _.template($('#task-list-template').html()),
    'render': function() {
        var that = this;
        var tasks = new Tasks();
        tasks.fetch( {
            success: function() {
                that.$el.html( that.template( { 'tasks': tasks } ) );
            }
        })
    }
});
var TaskEditView = Backbone.View.extend({
    'el': '.page',
    'template': _.template($('#task-edit-template').html()),
    'render': function(options) {
        if(options.id) {
            var that = this;
            var existingTask = new Task({id: options.id});
            console.log("existingTask");
            console.log(existingTask);
            existingTask.fetch({
                success: function(gotObject) {
                    console.log(existingTask.toJSON());
                    console.log("existing task id = " + existingTask.task.id);
                    console.log("existing task task = " + existingTask.task.task);
                    that.$el.html( that.template( { task: existingTask.task } ) );
                }
            });
        }
        else {
            var task = new Task();
            this.$el.html( this.template( { task: null } ) );
        }
    },
    'events': {
        'submit .edit-task-form': 'saveTask'
    },
    saveTask: function(ev) {
        var taskDetails = $(ev.currentTarget).serializeObject();
        var task = new Task;
        console.log(taskDetails);
        task.save(taskDetails, {
            success: function(task) {
                router.navigate('', {trigger: true});
            },
            error: function(model, response) {
                var responseObj = $.parseJSON(response.responseText);
                console.log('Type: ' + responseObj.error + ' Message: ' + responseObj.message);
            }
        });
        return false;
    }
});
var Router = Backbone.Router.extend({
    routes: {
        '' : 'home', // intentionally blank for the home page
        'new' : 'editTask',
        'edit/:id' : 'editTask'
    }
});
// Display logic
var taskListView = new TaskListView({ });
var taskEditView = new TaskEditView({ });
var router = new Router();
router.on('route:home', function() {
    taskListView.render();
});
router.on('route:editTask', function(id) {
    taskEditView.render({id: id});
});
Backbone.history.start();

谢谢你的帮助!

大卫

可以这样修改你的解析:

'parse': function( apiResponse ){
    if( _.isArray(apiResponse) ) return apiResponse;
       return apiResponse.task;
}