javascriptphpbackbone.jsaura.js

Backbone collection fetch not firing


I'm new to backbone and I'm trying to send and receive data from the server in Json format. It just won't work. Here's my code (BTW, I'm using backbone aura):

Collection

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;

});

Model

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

var Message = sandbox.mvc.Model({

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

});

return Message;
});

View

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;

});

Main

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.
        }
    });
};
});

I've check logs and it seems that the ajax request (collection.fetch()) is not firing or is not able to communicate with the server. How can I fix this?


Solution

  • The problem is with the Backbone.LocalStorage plugin. When you assign Collection.localStorage, the plugin takes over the fetch command and reads the data from local storage instead of the server.

    See my answer in this SO question on some options on how to solve this.