JavaScript流畅的界面,如Angular.js中的
我正在使用Angular.js,尤其是JavaScript流畅的界面,如Angular.js中的,javascript,angularjs,interface,fluent,Javascript,Angularjs,Interface,Fluent,我正在使用Angular.js,尤其是$http和以下代码: $http.get('test.url').onsuccess(function(res){}); 我想知道怎样才能编写这样的结构。第一次尝试是在Angular.js代码中确定这一点,但我的JavaScript知识可能太弱,无法理解所有代码 因此,我自己尝试了以下方法: var command = function(){ this.execute = function(cmd){ setInterval(fu
$http
和以下代码:
$http.get('test.url').onsuccess(function(res){});
我想知道怎样才能编写这样的结构。第一次尝试是在Angular.js代码中确定这一点,但我的JavaScript知识可能太弱,无法理解所有代码
因此,我自己尝试了以下方法:
var command = function(){
this.execute = function(cmd){
setInterval(function(){
// What to call here?
}, 60 * 60, 1000);
return this;
};
this.onsuccess = function(callBack){
return this;
}
}
var bla = new command();
bla.execute("myCommand").onsuccess(function(result){
console.log(result);
});
我很肯定我的代码是错的。我需要调用什么才能让所有这些东西正常工作?这些流畅的接口与其他流畅的接口不同,因为每个方法都返回一个
承诺jQuery
有自己的promise方法,但可以使用q
<代码>角度
使用q
($q
)。您还可以使用q
进行xhr请求以外的异步操作。这些都是承诺。它们是一种抽象,允许您轻松地编写延续。这是关于它的
一个非常天真和基本的方法来做你在这里尝试的事情是:
var command = function(){
var cbs = [];
this.execute = function(cmd){
setInterval(function(){
cbs.forEach(function(f){ f();}); // call all callbacks
}, 60 * 60, 1000);
return this;
};
this.onsuccess = function(callBack){
// a return this here would require a queue- and do return a different generic command
// so we're not doing it here
cbs.push(callBack); // add a callback to the list of handlers
}
}
有了像蓝鸟这样的承诺库,您可以:
Promise.delay(1000).then(function(yourThing){
});
Angular可以使用承诺,但您可以在没有承诺的情况下实现相同类型的功能:
var command = function(){
this.execute = function(cmd){
var theCallback;
setInterval(function(){
if(typeof theCallback === "function"){
theCallback();
}
}, 60 * 60, 1000);
return {
onsuccess: function(callback){
theCallback = callback;
}
};
};
}
var bla = new command();
bla.execute("myCommand").onsuccess(function(result){
console.log(result);
});
这些都是承诺。它们是一种抽象,允许您轻松地编写延续。这是关于它的。