创建一个 dojo 小部件以通过请求加载另一个页面

Creating a dojo widget to load another page via request

我希望这个小部件显示 http://localhost:8080/webapp/trending 页面上的内容:

<div data-dojo-type="js/widget/SATrending"></div>

现在它没有将内容加载到页面上,我不确定我错过了什么。

JS (js/widget/SATrending):

require([
"dojo/_base/declare",
"dojo/dom-construct",
"dojo/parser",
"dojo/ready",
"dijit/_WidgetBase",
"dojo/request"],
function(declare, domConstruct, parser, ready, _WidgetBase, request) {
    declare("js/widget/SATrending",[_WidgetBase], {
        top: 10,
        constructor: function() {
        },
        postMixInProperties: function() {
        },
        buildRendering: function() {
            var txt;

            request("http://localhost:8080/webapp/trending").then(
                    function(text) {
                        txt: text;
                    },
                    function(error) {});

            this.domNode = txt;
        },
        /*
         * Setters
         */
        setTopAttr: function(top) {
            this.top = top;
        },
        postCreate: function() {
        },
        startUp: function() {
        }
    }); 
});

你有几个问题。首先,在您的成功回调中,txt: text 无效 JavaScript。其次,您可能希望将 txt 分配给 this.domNode.innerHTML,而不仅仅是 this.domNode.

然而,最重要的是,this.domNode = txt; 永远不会做您可能期望的事情,因为 txt 实际上没有更新 直到请求异步完成,但您在发送请求后立即设置 this.domNode

这里是一个将您的 buildRendering 代码重组为应该实际工作的代码的示例:

this.inherited(arguments);
var self = this;

request("http://localhost:8080/webapp/trending").then(
    function(text) {
        self.domNode.innerHTML = text;
    },
    function(error) {});

关于您的代码的其他说明:

  • 如果您定义了小部件生命周期方法(postMixInProperties、buildRendering、postCreate、startup),请不要忘记调用 this.inherited(arguments)。 (constructor 默认链接,所以你不应该在那里调用它。)
  • startup 应该有一个小写的 u.
  • 您可以使用 ContentPane 及其 href 属性 来更轻松地完成您想在这里做的事情。