尝试学习创建独立的game.js
插件。
调用依赖于其他两个独立函数的结果的函数的最佳实践是什么?有时只调用一个函数。
例如:
如何实现这个逻辑:result = C(B(A()));
在其他页面;只需要调用C();
我看了this answer,但它与我的要求不符。
例如;一些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");
}
});
没有将所有内容包装在一个函数中的原因;有些函数被多次调用。
例如:
有时我想在不显示弹出窗口的情况下刷新页面中的点数。 其他一些我想要显示弹出窗口的地方有不同的要求。
我担心
答案 0 :(得分:1)
根据您的第一个要求,您希望能够根据使用情况以不同方式调用popup(msg)。您可以以不同的方式构造代码并使用模块模式,将当前函数作为私有函数并公开几个不同的函数:
$(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);
});
然后,根据使用情况,您可以致电:
module.showPopup(msg); //basically a wrapper to your existing function
或:
module.getDataPointsPopup(userID);
refreshDataPoints()& getDataPointsPopup()方法依赖于 promise 和 deferred 对象,在您链接的答案中描述,我认为这将满足您的要求#39 ;能够将这些方法联系起来并处理成功与否失败( then()方法接受2个参数)。