1

我是主干新手,我正在尝试以 Json 格式从服务器发送和接收数据。它只是行不通。这是我的代码(顺便说一句,我正在使用骨干光环):

收藏

define(['sandbox', '../models/message'], function(sandbox, Message) {
'use strict';

var Messages = sandbox.mvc.Collection({
    model: Message,
    url: '/messagelist.php',
    localStorage: new sandbox.data.Store('messages-backbone-require'),
    parse: function(response){
        return response.rows;
    }
});

return Messages;

});

模型

define(['sandbox'], function(sandbox) {
'use strict';

var Message = sandbox.mvc.Model({

    defaults: {
        opened: '',
        messageid: '',
        phonenumber: '',
        numbername: '',
        text: ''
    },
    parse: function(data){
        return data;
    }

});

return Message;
});

看法

define(['sandbox', '../models/message', 'text!../templates/incoming_messages.html'], function(sandbox, Message, incomingMessagesTemplate) {
'use strict';

var AppView = sandbox.mvc.View({
    widgetTemplate: sandbox.template.parse(incomingMessagesTemplate),

    events: {
        'click .refresh': 'refresh'
    },

    initialize: function() {
        this.$el.html(this.widgetTemplate);
        sandbox.events.bindAll(this);
        this.collection.bind('createMessageList', this.createMessageList);
    },

    createMessageList: function() {
        // Will work with the received data here
    },

    render: function() {
        var handle = 'h4';
        this.$el.draggable({handle: handle});
        this.createMessageList();
    },

    refresh: function() {
        this.createMessageList();
    }


});

return AppView;

});

主要的

define(['sandbox', './views/app', './collections/messages'], function(sandbox, AppView, Messages) {
'use strict';

return function(options) {
    var messages = new Messages();

    new AppView({
        el: sandbox.dom.find(options.element),
        collection: messages
    }).render();

    messages.fetch({
        data: {
            type: 'incoming',
            offset: 0,
            offsetcount: 25
        },
        type: 'GET',
        success: function() {
            console.log(messages.models); // Shows an empty array.
        }
    });
};
});

我检查了日志,似乎 ajax 请求 (collection.fetch()) 没有触发或无法与服务器通信。我怎样才能解决这个问题?

4

1 回答 1

2

问题出在 Backbone.LocalStorage 插件上。当您分配Collection.localStorage时,插件会接管fetch命令并从本地存储而不是服务器读取数据。

有关如何解决此问题的一些选项,请参阅我在此 SO 问题中的回答。

于 2013-01-10T11:09:36.517 回答