2

Good day,

I have created an object that will manage data access. My app will be using a couple different datastores, so I have created a simple factory to switch between providers:

var dataProvider = {
company: {
    getAllCompanies: function (callback) {
        var impl = factory.createProvider(implInstance.current)
        impl.company.getAllCompanies(callback);
    }
}
projects: {
    getAllProjects: function (callback) {
        var impl = factory.createProvider(implInstance.current)
        impl.projects.getAllProjects(callback);
    }
}
}

That is all well and good, but I'd rather have my impl variable at the dataProvider level. I'm unsure how I would properly access it though, as 'this' doesn't provide me the right scope when I'm nested so deeply. I'd like something like the following:

var dataProvider = {
impl: function () { return factory.createProvider(implInstance.current) },
company: {
    getAllCompanies: function (callback) {
        //THIS WON'T WORK
        this.impl.company.getAllCompanies(callback);
    }
}

Thanks!

1
  • Try this.impl().company.getAllCompanies(callback); as impl seems to be a function. Or maybe even; impl: function () { return factory.createProvider(implInstance.current) }() to enable this.impl.company.getAllCompanies(callback);, Commented Jun 27, 2012 at 14:44

1 Answer 1

4

You'd want to use the module design pattern for this:

var dataProvider = (function () {
    var getImpl = function () {
        return factory.createProvider(implInstance.current);
    };
    return {
        company: {
            getAllCompanies: function (callback) {
                getImpl().company.getAllCompanies(callback);
            }
        },
        projects: {
            getAllProjects: function (callback) {
                getImpl().projects.getAllProjects(callback);
            }
        }
    }
})();
Sign up to request clarification or add additional context in comments.

4 Comments

Oops, I'm actually getting a message indicating that in the "impl" is undefined on line that says: impl.company.getAllCompanies(callback); Any ideas?
Sorry Chris, I've edited above. This will lookup the impl value the first time it's requested and cache the looked up value for future use. Let me know if that works.
Will the provider implementation actually get cached to to the "impl" var? (I don't actually want to cache, I'm switching providers on the fly depending on if the iPad has connectivity or not, but I'm curious if there's something I'm missing)
Actually it won't as it stands, sorry! Because impl is never assigned a value. I've updated the answer to make this clearer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.