dojo declare correct way

后端 未结 2 1681
無奈伤痛
無奈伤痛 2021-01-24 10:36

file: dojo/dir1/utils/XmlJsonUtils.js

// Author: Rajat Khandelwal

define([
    \"dojo/_base/declare\" // declare
    ], function(declare){
      r         


        
相关标签:
2条回答
  • 2021-01-24 10:50

    Your class should not have to have the constructor method defined, dojo.declare is supposed to handle this.. However, doing so doesnt hurt, simply define a blank constructor: function() { }. I suspect youre facing some sort of bug.

    The define is as should be, 'define' is used for the require-scope, when running require(["my.module"]), its expected to have a define method, which returns the base class via declare.

    file: dojo/dir1/utils/XmlJsonUtils.js:

    define([
       // requirements
       "dojo/_base/declare", 
       "dir1/utils/Toolkit" // sample in-package dependency
       "./Toolkit"     // Same as Above
    ], function (declare) {
       // no slash separator, use dot with declare, 
       // use a reference and return on last line
       var Klass = declare(
       /// declaredClass: string, moduleUrl with dot-separater + filename /.js//
           "dir1.utils.XmlJsonUtils",
       /// base class: Array(mixins)
           [],
       /// class scope
           {
               _methodMeantToBePrivate: function() { },
               randomInstanceMethod: function() { }
           }
       ); // end declare
    
    
       // set any aliases, which you want to expose (statics)
    
       Klass.StaticCallable = function() {
           // careful with your scope access inhere
       }
    
       // return the declared class to 'define'
       return Klass;
    }); // end define
    

    This way (you must have a reference, either pulled in with require or getObject), you could use the StaticCallable function without initializing / constructing an instance of the module. AMD compliant syntax is like so:

    require(["dir1/utils/XmlJsonUtils"], function(xmlUtils) {
       xmlUtils.StaticCallable();
    });
    

    or if previously required

    var xmlUtils = dojo.getObject("dir1.utils.XmlJsonUtils")
    xmlUtils.StaticCallable();
    

    A specific example could be a versatile class like the following, where both instance and static access is possible. Base class defines 'tools', derived class defines the variables the 'tools' operate on - and if instantiated, the default topics can be subscribed - [ MessageBusBase | MessageBus ]

    0 讨论(0)
  • 2021-01-24 11:06

    The issue: in your code.

    return declare("dir1.utils.XmlJsonUtils",[],{
        parseXml : function (xml) {
    

    Instead of dir1.utils.XmlJsonUtils use dir1/utils/XmlJsonUtils, i.e., use slashes instead of dots in your function declaration.

    0 讨论(0)
提交回复
热议问题