Giter Site home page Giter Site logo

backbone.force's Introduction

Description

Backbone.Force is a plugin library that enables Force.com connectivity to Backbone.js Model and Collection types. In the back it uses forcetk library provided by Salesforce.com team.

Usage

To initialize it you need to call initialize function and pass it authorized forcetk.Client object:

Backbone.Force.initialize(forcetkClient);

Model

Defining Model type:

var Opportunity = Backbone.Force.Model.extend({
    type:'Opportunity'
});

Fetching Model by Id:

var myOpp = new Opportunity({
    Id:'OPPORTUNITY_ID'
});

myOpp.fetch({
    success:function (model, response) {
        alert('Fetched opportunity name: ' + model.get('Name'));
    },
    error:function (model, response) {
        alert('Error fetching Opportunity!');
    }
});

Updating Model (works exactly the same as Backbone.Model udpates):

myOpp.set('Name', 'New Opp name');
myOpp.save(null, {
    success:function (model, response) {
        alert('Model updated successfully!');
    },
    error:function (model, response) {
        alert('Updating model failed!');
    }
});

Optionally you can define which fields you would like to fetch:

var Opportunity = Backbone.Force.Model.extend({
    type:'Opportunity',
    fields:['Name', 'ExpectedRevenue']
});

Collection

Fetching multiple models requires defining new Collection type with model and query properties set. In this case query property should contain only WHERE soql clause.

var OppsCollection = Backbone.Force.Collection.extend({
            // Model type
            model:Opportunity,
            // WHERE part of SOQL query
            query:'WHERE IsWon = TRUE'
        }),
        myOppsCollection = new OppsCollection();

// Fetching all Opportunities
myOppsCollection.fetch({
    success:function (collection, response) {
        alert('Found: ' + collection.length + ' opps');
    },
    error:function (collection, response) {
        alert('Fetching opportunities failed!');
    }
});

Executing queries requies defining new Colleciton type with query property set.

var SOQLCollection = Backbone.Force.Collection.extend({
            // SOQL query
            query:'SELECT Id, Name, ExpectedRevenue, ' +
                    '(SELECT Subject, DurationInMinutes FROM Events), ' +
                    'Account.Id, Account.Name FROM Opportunity WHERE IsWon = TRUE'
        }),
        mySOQLCollection = new SOQLCollection();

// Executing query
mySOQLCollection.fetch({
    success:function (collection, response) {
        var accounts = [];
        collection.each(function (model) {
            // Only first level objects are mapped to Backbone.Model types, that is why Account is a standard JS object
            accounts.push(model.get('Account').Name);
        });

        alert('Found accounts:\n\n' + accounts.join('\n'));
    },
    error:function (collection, response) {
        alert('Executing SOQL query failed!');
    }
});

Demo

Snippet below will work in Safari browser on desktop or on mobile device using PhoneGap/Cordova and ChildBrowser plugin. It uses yet another project of mine that is called forcetk.ui.

<!DOCTYPE html>
<html>
<head>
    <title>forcetk.ui demo</title>

    <script type="text/javascript" src="scripts/libs/jquery-1.8.1.js"></script>

    <script type="text/javascript" src="scripts/libs/forcetk.js"></script>
    <script type="text/javascript" src="scripts/libs/forcetk.ui.js"></script>

    <script type="text/javascript" src="scripts/libs/underscore.js"></script>
    <script type="text/javascript" src="scripts/libs/backbone.js"></script>
    <script type="text/javascript" src="scripts/libs/backbone.force.js"></script>

    <script type="text/javascript">

        function login() {
            // Salesforce login URL
            var loginURL = 'https://login.salesforce.com/',

            // Consumer Key from Setup | Develop | Remote Access
                    consumerKey = 'CONSUMER_KEY',

            // Callback URL from Setup | Develop | Remote Access
                    callbackURL = 'https://login.salesforce.com/services/oauth2/success',

            // Instantiating forcetk ClientUI
                    ftkClientUI = new forcetk.ClientUI(loginURL, consumerKey, callbackURL,
                            function forceOAuthUI_successHandler(forcetkClient) { // successCallback
                                console.log('OAuth success!');

                                var Force = Backbone.Force;
                                Force.initialize(forcetkClient);

                                // ********** Fetching Model **********

                                // Creating Opportunity type that maps to Salesforce Opportunity object
                                var Opportunity = Force.Model.extend({
                                            type:'Opportunity',
                                            fields:['Name', 'ExpectedRevenue']
                                        }),

                                // Creating instance of Opportunity type with specified id
                                        myOpp = new Opportunity({
                                            Id:'006E0000004sgoo'
                                        });

                                // Fetching opportunity with specified id
                                myOpp.fetch({
                                    success:function (model, response) {
                                        alert('Fetched opportunity name: ' + model.get('Name'));
                                    },
                                    error:function (model, response) {
                                        alert('Error fetching Opportunity!');
                                    }
                                });

                                // ********** Fetching Collection of Models **********

                                var OppsCollection = Force.Collection.extend({
                                            model:Opportunity,
                                            query:'WHERE IsWon = TRUE'
                                        }),
                                        myOppsCollection = new OppsCollection();

                                // Fetching all Opportunities
                                myOppsCollection.fetch({
                                    success:function (collection, response) {
                                        alert('Found: ' + collection.length + ' opps');
                                    },
                                    error:function (collection, response) {
                                        alert('Fetching opportunities failed!');
                                    }
                                });

                                // ********** Executing SOQL query **********

                                var SOQLCollection = Force.Collection.extend({
                                            query:'SELECT Id, Name, ExpectedRevenue, ' +
                                                    '(SELECT Subject, DurationInMinutes FROM Events), ' +
                                                    'Account.Id, Account.Name FROM Opportunity WHERE IsWon = TRUE'
                                        }),
                                        mySOQLCollection = new SOQLCollection();

                                // Executing query
                                mySOQLCollection.fetch({
                                    success:function (collection, response) {
                                        var accounts = [];
                                        collection.each(function (model) {
                                            accounts.push(model.get('Account').Name);
                                        });

                                        alert('Found accounts:\n\n' + accounts.join('\n'));
                                    },
                                    error:function (collection, response) {
                                        alert('Executing SOQL query failed!');
                                    }
                                });

                            },

                            function forceOAuthUI_errorHandler(error) { // errorCallback
                                alert('OAuth error!');
                            });

            // Initiating login process
            ftkClientUI.login();
        }

    </script>

</head>
<body onload="login()">
<h3>Backbone.Force tests</h3>
</body>
</html>

Examples

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.