Luke Smith![]()
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.
});
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();
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) {...});
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!
}
});
{ 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.
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.
<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');
});
});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