具有异步设置属性的 JS 对象
JS Object with an asynchronously set property
我使用异步函数设置 Person.name(想想ajax调用)。不幸的是,我仍然想使用对象中的其他函数,而不必将它们放在回调中。
如何使用依赖于对象的异步设置属性的函数?
要执行的代码:
var user = new Person();
user.setName(); // This is async.
var is_jennifer = user.isItJennifer(); // Oh no! the user's name may not be defined yet!
...
...
var is_tom = user.isItTom(); // Much later in the code I need the async property again. I don't want to cram all of this into a callback whenever I setName.
具有异步方法setName()
的对象。
function Person() {
// Properties
this.name = null;
this.setName = function() {
this.name = NameModelThing.getName(); // Oh no! getName returns a result asynchronously.
}
this.isItJennifer = function() {
return (this.name == 'Jennifer') ? true : false;
}
this.isItTom = function() {
return (this.name == 'Tom') ? true : false;
}
}
如果你对 ajax 请求使用 jquery,你可以通过传递 async: false 作为一个选项来使请求不异步。
http://api.jquery.com/jQuery.ajax/
作为替代方法,您可以使用一种模式,在加载页面时对 Person 对象进行某种初始化,并从那里使用回调:
var user = new Person();
user.fetch({
success: function() {
// code when user ready here.
}
});
相关文章:
- 查看JS对象的所有键,甚至是getter定义的键
- 在URL中传递JS对象
- 当属性不一致时,如何根据属性对JS对象列表进行排序
- JS对象密钥序列
- 在ajax调用中阻止来自JS对象的函数
- 属性未添加到JS对象
- 将字符串转换为JS对象
- 使用lodash查找具有truthy值的JS对象的属性
- 将toString方法暴露给nashorn中的js对象
- JSON数组转换为JS对象数组
- 将js对象更改为使用嵌套的可观察数组敲除js视图模型
- 设置1400个Raphael.js对象的不透明度动画会影响动画性能
- 以非ajax方式将js对象传递给mvc操作
- JS对象->来自jquery ajax的JSON提交->php迭代
- XMLHttpRequest发送JS对象
- 使用游标循环将JS对象添加到数组中
- 动态(重新)创建iframe内容不会重置Chrome中的JS对象
- 将JS对象数组转换为嵌套形式的最有效方法
- 在知道对象值的情况下,确定数组中JS对象的索引
- JS对象文字中的方法和子方法