【问题标题】:Dojo - Json REST call in custom module contructorDojo - 自定义模块构造函数中的 Json REST 调用
【发布时间】:2014-01-08 21:19:11
【问题描述】:

我正在使用 dojo 1.9 编写一个自定义模块,并且我有这段代码用于声明它:

define(["dojo/_base/declare", "dojo/store/JsonRest"], function(declare, JsonRest){
    return declare(null, {
        user: 'Not set',
        constructor: function(id){
            var store = new JsonRest({
                target: "myurl"
            });
            store.get('user').then(function(item){
                console.log(item.user);
                this.user = item.user;
            });
        },
        getUser: function(){
            return this.user;
        }
    });
});

在另一个文件中,我使用以下代码:

require(["modules/demo/demo"], function(demo){
        var x = new demo('7');
        alert(x.getUser());


    });

我明白我的问题:在 json/rest 调用完成之前调用 getUser() 函数,所以这个函数

alert(x.getUser());

总是返回“未设置”,因为 json 值仍未加载。如何让 getUser 函数等待它?

p.s.:我确信 json 休息请求运行良好,因为控制台日志没问题...

提前致谢

【问题讨论】:

    标签: json rest dojo


    【解决方案1】:

    这就是 Ajax 的本质 :)

    一种方法是使用store.get()返回的dojo/Deferred对象。

    define([
        "dojo/_base/declare", 
        "dojo/_base/lang", 
        "dojo/store/JsonRest"
    ], function(
        declare, 
        lang, 
        JsonRest
    ){
        return declare(null, {
            user: 'Not set',
            _initialized: null,
            constructor: function(id){
                var store = new JsonRest({
                    target: "myurl"
                });
                this._initialized = store.get('user');
    
                this._initialized.then(lang.hitch(this, function(item){
                    console.log(item.user);
                    this.user = item.user;
                }));
            },
            initialize: function() {
                return this._initialized;
            },
            getUser: function(){
                return this.user;
            }
        });
    });
    ....
    
    require(["modules/demo/demo"], function(demo){
        var x = new demo('7');
        x.initialize().then(function() {
            alert(x.getUser());
        });
    });
    

    示例:http://fiddle.jshell.net/6mgwh/

    【讨论】:

    • @michaelramin 啊,我没有测试它,它可能不起作用,因为构造函数中的回调没有在正确的范围内运行。更新了答案,并添加了一个小提琴。
    猜你喜欢
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 2013-07-27
    • 1970-01-01
    • 2011-10-08
    • 2023-03-12
    • 2012-12-22
    • 2016-01-21
    相关资源
    最近更新 更多