将初始化参数设置为自定义小部件的推荐模式

Recommended pattern for setting initialization parameters to custom widget

我正在创建我自己的基于模板的小部件,并且我试图在创建时通过构造函数传递一些对象,就像这样

var widget = new myWidget(obj1, obj2, obj3);

我的小部件构造函数看起来像

constructor: function(param1, param2, param3)

但是我遇到了一些错误,发现它们是由于 _WidgetBase 功能(特别是 create 方法)在第一个和第二个参数中需要一些特殊的东西。

create: function(params, srcNodeRef)

因此,为了避免我的参数破坏参数,以及预期在位置一和位置二的 srcNodeRef,我不得不像这样将我的参数移动到第二个位置之后

constructor: function (params, srcNodeRef, myParam1, myparam2, myParam3)

但与在普通面向对象语言(例如 c#)中实例化对象的常用方法相比,这自然不是解决此问题的预期方法

我的问题是,是否有推荐的模式将初始化参数传递给自定义小部件构造函数,从而避免必须记住第一个和第二个参数位置已保留的问题?

注意: 一个重要的注意事项是,无论我向小部件发送什么参数,都必须在 before postCreate 执行之前执行或可用,就像我将它们传递给构造函数一样。

实际上,有一种 "dojo" 方法可以将参数传递给您的小部件:

var widget = new myWidget({obj1: obj1, obj2: obj2});

在您的小部件实例中,这些对象将引用 this.obj1, this.obj2。您不必重写构造函数。

来自 _WidgetBase 的 dojo 源关于此主题的一些评论:

//////////// INITIALIZATION METHODS ///////////////////////////////////////

        /*=====
        constructor: function(params, srcNodeRef){
            // summary:
            //      Create the widget.
            // params: Object|null
            //      Hash of initialization parameters for widget, including scalar values (like title, duration etc.)
            //      and functions, typically callbacks like onClick.
            //      The hash can contain any of the widget's properties, excluding read-only properties.
            // srcNodeRef: DOMNode|String?
            //      If a srcNodeRef (DOM node) is specified:
            //
            //      - use srcNodeRef.innerHTML as my contents
            //      - if this is a behavioral widget then apply behavior to that srcNodeRef
            //      - otherwise, replace srcNodeRef with my generated DOM tree
        },
        =====*/

我为 Kirill 的回答 +1,因为这是最简单的。但从其他评论看来,您可能需要根据输入修改输入或初始化其他变量。

如果是这样,请查看 postMixinProperties lifecycle method 并在您的小部件中覆盖它。如果您的小部件是模板化的并且模板需要经过处理的数据,那么您将需要它。在这里,您可以按预期使用 this 引用您的属性。

    postMixInProperties: function(){
        // summary:
        //      Called after the parameters to the widget have been read-in,
        //      but before the widget template is instantiated. Especially
        //      useful to set properties that are referenced in the widget
        //      template.
        // tags:
        //      protected
    },

不要忘记在这里调用 this.inherited(arguments);,就像在所有 dijit 生命周期方法中一样。

为您的属性定义 setters 是处理这些属性的另一种方法。如果模板将使用这些属性,您将需要它。来自 Writing Widgets page 的 setter 示例。所以这里 'open' 将是传递给构造函数或小部件模板中的参数名称。

     _setOpenAttr: function(/*Boolean*/ open){
         this._set("open", open);
         domStyle.set(this.domNode, "display", open ? "block" : "none");
     }