Reputation: 1054
Trying to learn to create a standalone game.js
plugin.
What is the best practice to call a function that depends on the result of two other separate functions? and sometimes call one function only.
for example:
How to achieve this logic: result= C( B( A() ) );
in other pages; only need to call C();
I read this answer, but it didn't match my requirements.
for example; some block of jquery:
userID = 123;
$(function () {
points = load_points(userID); // load points
refresh(points); // refresh points' span and animate
popup(points); // pop up user the points
function load_points(userID) {
// Read points from a PHP/MySQL page using Ajax then Return points
// sample output: 100 point
return result;
}
function refresh(p) {
// update span value then animate
$("#spanID").text(p);
$("#spanID").slideDown(1000);
return true; // return true after 1000 ms
}
function popup(msg) {
// if #spanID value updated and animated
// ; show overlay popup with points.
// using this popup plugin here
//http://dev.vast.com/jquery-popup-overlay/
alert("You win " + msg+ " Points");
}
});
The reason not wrapping everything in one function; is some functions are called several times.
For example:
Sometimes I want to refresh points in a page without showing the popup. Some other places I want to show the popup with different requirements.
I am concern about
Upvotes: 0
Views: 154
Reputation: 170
On your first requirement, you want to be able to call popup(msg) in different ways depending on usage. You could perhaps structure your code differently and use the module pattern, having your current functions as private and exposing a couple of different functions:
$(document).ready(function() {
var module = (function() {
var loadPoints = function(userID) {
var root = 'https://jsonplaceholder.typicode.com';
return $.ajax({
url: root + '/posts/1',
method: 'GET'
});
};
var refresh = function(data) {
alert(data.title)
};
var popup = function(msg) {
alert(msg);
};
var refreshDataPoints = function(userID) {
loadPoints(userID).then(refresh);
};
var getDataPointsPopup = function(userID) {
loadPoints(userID).then(refresh).then(popup);
};
// Public API
return {
showPopup: popup,
refreshDataPoints: refreshDataPoints,
getDataPointsPopup: getDataPointsPopup
};
})();
module.refreshDataPoints(1);
});
Then, depending on usage, you could call:
module.showPopup(msg); //basically a wrapper to your existing function
or:
module.getDataPointsPopup(userID);
The refreshDataPoints() & getDataPointsPopup() methods rely on promise and deferred objects, described in the answer you linked, I think this would satisfy the requirement that you're able to chain these methods and handle success & failure (the then() method accepts 2 parameters).
Upvotes: 1