Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to get property 'collection' of undefined or null reference when calling sync(); #224

Open
Liero opened this issue Nov 23, 2017 · 1 comment

Comments

@Liero
Copy link

Liero commented Nov 23, 2017

when I call myModel.sync(), I'm getting

Unable to get property 'collection' of undefined or null reference

import { Model } from 'backbone';
import { LocalStorage } from 'backbone.localstorage';

class UserModel extends Model {
    constructor() {
        super();
        this.localStorage = new LocalStorage('api/Account');
    }
    url() {  return "/api/Account"   }
    sync(){
        return super.sync();
    }
    fetch() {
        return super.fetch({
            crossDomain: true, 
            xhrFields: {
                withCredentials: true
            },
            ajaxSync: true,            
        });
    }
    save() {
        return super.save({}, { ajaxSync: false });
    }
}

My scenario is, that I have a readonly REST Resource api/Account that returns info about current user. I want to support offline scenarios. I thought I can call synch at the app startup and it would load info about current user and store it in localstorage

@scott-w
Copy link
Collaborator

scott-w commented Nov 23, 2017

Hi @Liero

This might be because Backbone doesn't have good support for being treated as an ES6 class. Try the following:

import { Model } from 'backbone';
import { LocalStorage } from 'backbone.localstorage';

const UserModel = Model.extend({
  localStorage = new LocalStorage('api/Account'),

  url: '/api/Account',

  fromServer() {
    return this.fetch({
      crossDomain: true,
      xhrFields: {
        withCredentials: true
     },
     ajaxSync: true
    });
  }
})

Then, instead of calling fetch, you call fromServer so you have the option to retrieve your credentials from Local Storage elsewhere in your app from the model.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants