• Register
  • Log In
  • Home
  • Quick Start
    • Configurator
    • Download YUI 3
  • Documentation
    • User Guides
    • Examples
    • Tutorials
    • API Docs
  • Community
    • Gallery
    • Blog »
    • Forums
    • YUI Theater
    • Calendar
  • Contribute
    • YUI on GitHub »
    • File a Ticket
    • View Tickets
    • Dashboard
  • Other Projects
    • YUI 2
    • YUI Compressor
    • YUI Doc »
    • YUI Builder
    • YUI PHP Loader
    • YUI Test
    • YUI Website
  • YUI
  • >
  • Community
  • >
  • Gallery

Gallery

Modules

  • Home
  • Featured
  • Popular
  • New
  • All

Documentation

  • FAQ
  • Developer FAQ
  • Developer Guide
  • Module Setup

Tag Cloud

davglass foxxtrot plugin nzakas ericf table node widget caridy solmsted event animation yql lsmith css satyam liferay io apipkin greghinch form jafl model datatable async

Context Navigation

    YUI Library is not responsible for bugs or support with this module. It is available as a free service. For support please contact the module owner with the provided links.

    JSON RPC (gallery-jsonrpc) on cdn

    Last Updated: 02/9/11
    + 1 -

    Luke Smith

    YUI Developer

    See 19 more by this user.

    Created: 10/20/10
    Last CDN Push: 05/9/12
    Build Tag: gallery-2012.05.09-20-27
    Project: YUI 3
    License: YUI BSD
    YUI Version: 3.3.0
    Free for use.

    Construction and configuration



    var api = new Y.JSONRPC({
    url: serviceUrl,
    methods: [ 'doThis', 'doThat' ], // optional. If provided, will disable construction-time API fetch
    version: 2, // optional. Default 2. RPC version. If > 1, will be identified in the outbound payload
    preload: false, // optional. Default true. Value false disables construction-time API fetch
    sync: false // optional. Default false. Value true enables synchronous io. Please don't do this.
    });

    Getting the remote API


    On construction, JSONRPC instances will send a GET request to the serviceUrl to fetch the API to simulate. The notification event that the API has been received from the server is apiready. If there is an issue in this transaction, the apierror event will fire instead.

    api.on("apiready", function () {
    // equivalent to api.doThis(...)
    this.doThis("Args", "are inline.", "Last arg can be a ", function (result) {...});
    });

    If preload config is false, you can manually request the API to be loaded.


    var api = new Y.JSONRPC({ url: serviceUrl, preload: false });
    // ... at some later point
    api.loadAPI();

    If you know the method names you're working with, you don't need to fetch them. Just name them in the methods configuration at instantiation. If methods is configured, the default preload will be disabled. Reenable it by passing a preload: true in the configuration, or just immediately call loadAPI();


    var api = new Y.JSONRPC({ url: serviceUrl, methods: [ 'doThis', 'doThat' ] });
    api.doThis("arg1", "arg2", function (result) { ... }); // immediately available

    The least desirable option is to configure the instance to operate synchronously. This will impact page performance, so have a very good reason to use this setting.


    var api = new Y.JSONRPC({ url: serviceUrl, sync: true });
    api._config.sync = false; // to set it back to async for API calls
    api.doThis();

    Using the remote API


    After fetching the API, the method names identified by the server will have proxies generated on the instance. All methods take any number of arguments, the last of which is the callback to execute with the response data. Arguments and callback are optional. You can pass N number of arguments, and not pass a callback, or pass just a callback with no arguments, or pass nothing.

    The JSON response will be parsed, and unless there was an error, the callback will be executed with the content of the response object's result property (see request/response object structure below).


    api.doThis(); // Just dispatch the method call to the server. Don't ask for a response
    api.doThis("with", "params"); // Again, don't ask for a response
    api.doThis(function (result) { ... }); // No parameter payload, but handle the response
    api.doThis("with", "params and a callback", function (result) {
    alert(result.message); // callback parameter is the JSON.parsed response
    });

    Another approach similar to supplying the method names in the configuration object is to use the generic exec function to call any remote method. Unlike the generated API methods, this method takes the remote method as the first arg and all outbound params as an array in the second arg. The callback is third.


    api.exec("doTheOtherThing", [ "arg1", "argN" ], function (result) {...});

    The callback can be either a success function or an io configuration object, allowing you to handle failures and other events. Note, the data configuration will be overridden.


    api.doThat("thing", {
    context: altThisObj, // set 'this' in the callbacks
    sync: true, // Seriously, don't do this, even for a single transaction
    on: {
    success: function (result) { // the function you would have passed as a final param
    // note the callback still receives the result property from JSON.parse()d data
    alert(result.message);
    },
    failure: function (err) {
    // Typically, err will be an object with properties "code" and "message", but may be different
    // (until a future revision) if there was an IO related error.
    Y.error("Uh oh! " + err.message);
    }
    }
    });

    The Y.jsonrpc() method is also provided as a wrapper for the instantiation and dispatch steps. It uses the same signature as exec, but with the serviceUrl prepended.


    Y.jsonrpc(serviceUrl, 'doThis', [ "params", "array" ], function (result) {...});

    Events


    As noted before, the apiready event fires when the API has been fetched from the server and the method proxies are in place. apierror fires if something went wrong in the request.

    apiready is configured with fireOnce, so subscribing after the API has been fetched will trigger immediate execution of the subscribed function.

    The only other method not exposed through IO's on:{...} configuration is the dispatch event, which wraps the actual call to Y.io. The event is preventable, and exposes the rpc payload object that will be sent to the server. This gives you the opportunity to customize this object.


    api.on("dispatch", function (e) {
    e.rpcPayload.params.push("bacon"); // Add an extra parameter
    e.rpcPayload.newProperty = "relevant info for the server";
    });

    Or stop the outbound call altogether.


    api.on("dispatch", function (e) {
    if (Y.Array.indexOf(e.rpcPayload.params, "bacon") === -1) {
    e.preventDefault(); // need moar bacon!
    }
    });

    Payload signature


    loadAPI expects an object with an array of method names stored in the methods property.

    { envelope: "JSON-RPC-1.0", // optional to override configured version to 1.0 (not spec'd?)
    methods: ["blarney", "blimey", "bilge", "rum"]
    }

    The API method calls are dispatched as a JSON.stringify()ed object in the post data. They have the following signature:


    {

    method: "doThis",
    params: [ "go", "team!" ],
    id: "some long YUI generated unique id", // Only present if a callback is passed to the method
    jsonrpc: "2.0" // Only present if the instance is configured with version greater than 1
    }

    The response should be sent with mime-type 'application/json' and be a valid JSON serialization of an object in this form for successful operations:


    {

    id: "some long YUI generated unique id",
    jsonrpc: "2.0", // Only present if the instance is configured with version greater than 1
    result: ???, // The data that will be passed to the success callback
    error: null
    }

    and this form for unsuccessful operations:


    {

    id: "some long YUI generated unique id",
    jsonrpc: "2.0", // Again, only if applicable
    error: {
    code: -32601,
    message: "Procedure not found."
    }
    }

    See http://en.wikipedia.org/wiki/JSON-RPC for more details.

    • Tags:
    • lsmith
    • json
    • jsonrpc
    • Download
    • Docs
    • Homepage
    • Bugs
    • Source
    • Example
    • Forum
    • History

    Use the JuicyFruit API to make an atomic call to the service API and alert the response message.

    Then create an instance configured to use JSONRPC version 1.0. When the initial fetch of the API has returned, subscribe via event delegation to all button elements classed with "delete" to call the remote method named deleteRecord, passing an id fetched from the node's data collection.

    Note, this example would be more efficiently accomplished by passing the methods configuration and skipping the api load + apiready subscriber step. But you know, it's for illustration and all.

    Code Sample

    <script src="http://yui.yahooapis.com/3.3.0/build/yui/yui-min.js"></script>
    YUI({
        //Last Gallery Build of this module
        gallery: 'gallery-2012.05.09-20-27'
    }).use('gallery-jsonrpc', function(Y) {
     
        // JuicyFruit API
        Y.jsonrpc('/jsonrpcService.php', 'doThat', [ "voodoo" ], function (result) {
            alert(result); // assumes server response { "result": "some message", "id": ... }
        });
     
        // or for lasting sugar
        var controller = new Y.JSONRPC({
            url: '/jsonrpcService.php',
            version: 1
        });
     
        controller.on('apiready') {
            Y.delegate("click", function () {
                controller.deleteRecord(this.getData("recordId"), updateUI);
            }, '#records', '.delete');
        });
     
    });

    Forum Posts

    No forum posts for this module.

    © 2006-2011 Yahoo! Inc. All rights reserved.
    All code on this site is licensed under the BSD License unless stated otherwise.
    About This Site · Security Contact Info