Namespace sap.uiModule: sap/ui/Global
The sap.ui
namespace is the central OpenAjax compliant entry point for UI related JavaScript functionality provided by SAP.
Component
or returns the instance of an existing Component
.sClassName
.window
.Component
or returns the instance of an existing Component
. If you want to look up an existing Component
you can call this function with a Component ID as parameter:
var oComponent = sap.ui.component(sComponentId);
To create a new instance of a component you pass a component configuration object into this function:
var oComponent = sap.ui.component({ name: "my.Component", url: "my/component/location", id: "myCompId1" });
Experimental API:Since 1.27.0. Support for asynchronous loading and the corresponding hints is still experimental and might be modified or removed completely again. It must not be used in productive code, except in code delivered by the UI5 teams. The synchronous usage of the API is not experimental and can be used without restrictions.
{string|object} | vConfig | ID of an existing Component or the configuration object to create the Component |
{string} | vConfig.name | Name of the Component to load |
{string} | vConfig.url? | Alternate location from where to load the Component. If a manifestUrl is given, this url specifies the location of the final component defined via that manifest, otherwise it specifies the location of the component defined via its name vConfig.name>/code>. |
{object} | vConfig.componentData? | Initial data of the Component (@see sap.ui.core.Component#getComponentData) |
{string} | vConfig.id? | sId of the new Component |
{object} | vConfig.settings? | mSettings of the new Component |
{boolean} | vConfig.async? | Indicates whether the Component creation should be done asynchronously (experimental setting) |
{object} | vConfig.asyncHints? | Hints for the asynchronous loading (experimental setting) |
{string[]} | vConfig.asyncHints.libs? | Libraries that should be (pre-)loaded before the Component (experimental setting) |
{string[]} | vConfig.asyncHints.components? | Components that should be (pre-)loaded before the Component (experimental setting) |
{Promise|Promise[]} | vConfig.asyncHints.waitFor? | @since 1.37.0 a Promise or and array of Promise s for which the Component instantiation should wait (experimental setting) |
{string} | vConfig.manifestUrl? | @since 1.33.0 Determines whether the component should be loaded and defined via the manifest.json |
{string} | vConfig.manifestFirst? | @since 1.33.0 defines whether the manifest is loaded before or after the Component controller. Defaults to sap.ui.getCore().getConfiguration().getManifestFirst() |
- Experimental:
- Since 1.27.0. Support for asynchronous loading and the corresponding hints is still experimental and might be modified or removed completely again. It must not be used in productive code, except in code delivered by the UI5 teams. The synchronous usage of the API is not experimental and can be used without restrictions.
- Since:
- 1.15.0
{sap.ui.core.Component|Promise} | the Component instance or a Promise in case of asynchronous loading |
When a name and a controller implementation object is given, a new controller class of the given name is created. The members of the implementation object will be copied into each new instance of that controller class (shallow copy). Note: as the members are shallow copied, controller instances will share all object values. This might or might not be what applications expect.
If only a name is given, a new instance of the named controller class is returned.
{string} | sName | The controller name |
{object} | oControllerImpl? | An object literal defining the methods and properties of the controller |
{void|sap.ui.core.mvc.Controller} | void or the new controller instance, depending on the use case |
The typical and only suggested usage of this method is to have one single, top level call to sap.ui.define
in one Javascript resource (file). When a module is requested by its name for the first time, the corresponding resource is determined from the name and the current configuration. The resource will be loaded and executed which in turn will execute the top level sap.ui.define
call.
If the module name was omitted from that call, it will be substituted by the name that was used to request the module. As a preparation step, the dependencies as well as their transitive dependencies, will be loaded. Then, the module value will be determined: if a static value (object, literal) was given, that value will be the module value. If a function was given, that function will be called (providing the module values of the declared dependencies as parameters to the function) and its return value will be used as module value. The framework internally associates the resulting value with the module name and provides it to the original requestor of the module. Whenever the module is requested again, the same value will be returned (modules are executed only once).
Example:
The following example defines a module "SomeClass", but doesn't hard code the module name. If stored in a file 'sap/mylib/SomeClass.js', it can be requested as 'sap/mylib/SomeClass'.
sap.ui.define(['./Helper', 'sap/m/Bar'], function(Helper,Bar) { // create a new class var SomeClass = function(); // add methods to its prototype SomeClass.prototype.foo = function() { // use a function from the dependency 'Helper' in the same package (e.g. 'sap/mylib/Helper' ) var mSettings = Helper.foo(); // create and return a sap.m.Bar (using its local name 'Bar') return new Bar(mSettings); } // return the class as module value return SomeClass; });
In another module or in an application HTML page, the sap.ui.require API can be used to load the Something module and to work with it:
sap.ui.require(['sap/mylib/Something'], function(Something) { // instantiate a Something and call foo() on it new Something().foo(); });
Module Name Syntaxsap.ui.define
uses a simplified variant of the unified resource name syntax for the module's own name as well as for its dependencies. The only difference to that syntax is, that for sap.ui.define
and sap.ui.require
, the extension (which always would be '.js') has to be omitted. Both methods always add this extension internally.
As a convenience, the name of a dependency can start with the segment './' which will be replaced by the name of the package that contains the currently defined module (relative name).
It is best practice to omit the name of the defined module (first parameter) and to use relative names for the dependencies whenever possible. This reduces the necessary configuration, simplifies renaming of packages and allows to map them to a different namespace.
Dependency to Modules
If a dependencies array is given, each entry represents the name of another module that the currently defined module depends on. All dependency modules are loaded before the value of the currently defined module is determined. The module value of each dependency module will be provided as a parameter to a factory function, the order of the parameters will match the order of the modules in the dependencies array.
Note: the order in which the dependency modules are executed is not defined by the order in the dependencies array! The execution order is affected by dependencies between the dependency modules as well as by their current state (whether a module already has been loaded or not). Neither module implementations nor dependants that require a module set must make any assumption about the execution order (other than expressed by their dependencies). There is, however, one exception with regard to third party libraries, see the list of limitations further down below.
Note:a static module value (a literal provided to sap.ui.define
) cannot depend on the module values of the depency modules. Instead, modules can use a factory function, calculate the static value in that function, potentially based on the dependencies, and return the result as module value. The same approach must be taken when the module value is supposed to be a function.
Asynchronous Contractsap.ui.define
is designed to support real Asynchronous Module Definitions (AMD) in future, although it internally still uses the the old synchronous module loading of UI5. Callers of sap.ui.define
therefore must not rely on any synchronous behavior that they might observe with the current implementation.
For example, callers of sap.ui.define
must not use the module value immediately after invoking sap.ui.define
:
// COUNTER EXAMPLE HOW __NOT__ TO DO IT // define a class Something as AMD module sap.ui.define('Something', [], function() { var Something = function(); return Something; }); // DON'T DO THAT! // accessing the class _synchronously_ after sap.ui.define was called new Something();
Applications that need to ensure synchronous module definition or synchronous loading of dependencies MUST use the old jQuery.sap.declare and jQuery.sap.require APIs.
(No) Global References
To be in line with AMD best practices, modules defined with sap.ui.define
should not make any use of global variables if those variables are also available as module values. Instead, they should add dependencies to those modules and use the corresponding parameter of the factory function to access the module value.
As the current programming model and the documentation of UI5 heavily rely on global names, there will be a transition phase where UI5 enables AMD modules and local references to module values in parallel to the old global names. The fourth parameter of sap.ui.define
has been added to support that transition phase. When this parameter is set to true, the framework provides two additional functionalities
- before the factory function is called, the existence of the global parent namespace for the current module is ensured
- the module value will be automatically exported under a global name which is derived from the name of the module
The parameter lets the framework know whether any of those two operations is needed or not. In future versions of UI5, a central configuration option is planned to suppress those 'exports'.
Third Party Modules
Although third party modules don't use UI5 APIs, they still can be listed as dependencies in a sap.ui.define
call. They will be requested and executed like UI5 modules, but their module value will be undefined
.
If the currently defined module needs to access the module value of such a third party module, it can access the value via its global name (if the module supports such a usage).
Note that UI5 temporarily deactivates an existing AMD loader while it executes third party modules known to support AMD. This sounds contradictarily at a first glance as UI5 wants to support AMD, but for now it is necessary to fully support UI5 apps that rely on global names for such modules.
Example:
// module 'Something' wants to use third party library 'URI.js' // It is packaged by UI5 as non-UI5-module 'sap/ui/thirdparty/URI' sap.ui.define('Something', ['sap/ui/thirdparty/URI'], function(URIModuleValue) { new URIModuleValue(); // fails as module value is undefined //global URI // (optional) declare usage of global name so that static code checks don't complain new URI(); // access to global name 'URI' works ... });
Differences to requireJS
The current implementation of sap.ui.define
differs from requireJS
or other AMD loaders in several aspects:
- the name
sap.ui.define
is different from the plaindefine
. This has two reasons: first, it avoids the impression thatsap.ui.define
is an exact implementation of an AMD loader. And second, it allows the coexistence of an AMD loader (requireJS) andsap.ui.define
in one application as long as UI5 or apps using UI5 are not fully prepared to run with an AMD loader sap.ui.define
currently loads modules with synchronous XHR calls. This is basically a tribute to the synchronous history of UI5. BUT: synchronous dependency loading and factory execution explicitly it not part of contract ofsap.ui.define
. To the contrary, it is already clear and planned that asynchronous loading will be implemented, at least as an alternative if not as the only implementation. Also check section Asynchronous Contract above.
Applications that need to ensure synchronous loading of dependencies MUST use the old jQuery.sap.require API.sap.ui.define
does not support plugins to use other file types, formats or protocols. It is not planned to support this in futuresap.ui.define
does not support the 'sugar' of requireJS where CommonJS style dependency declarations usingsap.ui.require("something")
are automagically converted intosap.ui.define
dependencies before executing the factory function.
Limitations, Design Considerations
- Limitation: as dependency management is not supported for Non-UI5 modules, the only way to ensure proper execution order for such modules currently is to rely on the order in the dependency array. Obviously, this only works as long as
sap.ui.define
uses synchronous loading. It will be enhanced when asynchronous loading is implemented. - it was discussed to enfore asynchronous execution of the module factory function (e.g. with a timeout of 0). But this would have invalidated the current migration scenario where a sync
jQuery.sap.require
call can load asap.ui.define
'ed module. If the module definition would not execute synchronously, the synchronous contract of the require call would be broken (default behavior in existing UI5 apps) - a single file must not contain multiple calls to
sap.ui.define
. Multiple calls currently are only supported in the so called 'preload' files that the UI5 merge tooling produces. The exact details of how this works might be changed in future implementations and are not yet part of the API contract
Experimental API:Since 1.27.0 - not all aspects of sap.ui.define are settled yet. If the documented constraints and limitations are obeyed, SAP-owned code might use it. If the fourth parameter is not used and if the asynchronous contract is respected, even Non-SAP code might use it.
{string} | sModuleName? | name of the module in simplified resource name syntax. When omitted, the loader determines the name from the request. |
{string[]} | aDependencies? | list of dependencies of the module |
{function|any} | vFactory | the module value or a function that calculates the value |
{boolean} | bExport? | whether an export to global names is required - should be used by SAP-owned code only |
- Experimental:
- Since 1.27.0 - not all aspects of sap.ui.define are settled yet. If the documented constraints and limitations are obeyed, SAP-owned code might use it. If the fourth parameter is not used and if the asynchronous contract is respected, even Non-SAP code might use it.
- Since:
- 1.27.0
In JSViews, this function allows both JSON notation in aggregation content as well as adding an extension point to an aggregation after the target control has already been instantiated. In the latter case the optional parameters oTargetControls and oTargetAggregation need to be specified.
{sap.ui.core.mvc.View|sap.ui.core.Fragment} | oContainer | The view or fragment containing the extension point |
{string} | sExtName | The extensionName used to identify the extension point in the customizing |
{createDefaultContent} | fnCreateDefaultContent? | Optional callback function creating default content, returning an Array of controls. It is executed when there's no customizing, if not provided, no default content will be rendered. |
{sap.ui.core.Control} | oTargetControl? | Optional - use this parameter to attach the extension point to a particular aggregation |
{string} | sAggregationName? | Optional - if provided along with oTargetControl, the extension point content is added to this particular aggregation at oTargetControl, if not given, but an oTargetControl is still present, the function will attempt to add the extension point to the default aggregation of oTargetControl. If no oTargetControl is provided, sAggregationName will also be ignored. |
{sap.ui.core.Control[]} | an array with 0..n controls created from an ExtensionPoint |
To instantiate an existing Fragment, call this method as: sap.ui.fragment(sName, sType, [oController]); The sName must correspond to an XML Fragment which can be loaded via the module system (fragmentName + suffix ".fragment.[typeextension]") and which defines the Fragment content. If oController is given, the (event handler) methods referenced in the Fragment will be called on this controller. Note that Fragments may require a Controller to be given and certain methods to be available.
The Fragment types "XML", "JS" and "HTML" are available by default; additional Fragment types can be implemented and added using the sap.ui.core.Fragment.registerType() function.
Advanced usage: To instantiate a Fragment and give further configuration options, call this method as: sap.ui.fragment(oFragmentConfig, [oController]); The oFragmentConfig object can have the following properties: - "fragmentName": the name of the Fragment, as above - "fragmentContent": the definition of the Fragment content itself. When this property is given, any given name is ignored. The type of this property depends on the Fragment type, e.g. it could be a string for XML Fragments. - "type": the type of the Fragment, as above (mandatory) - "id": the ID of the Fragment (optional) Further properties may be supported by future or custom Fragment types. Any given properties will be forwarded to the Fragment implementation.
If you want to give a fixed ID for the Fragment, please use the advanced version of this method call with the configuration object or use the typed factories like sap.ui.xmlfragment(...) or sap.ui.jsfragment(...). Otherwise the Fragment ID is generated. In any case, the Fragment ID will be used as prefix for the ID of all contained controls.
{string} | sName | the Fragment name |
{string} | sType | the Fragment type, e.g. "XML", "JS", or "HTML" |
{sap.ui.core.Controller} | oController? | the Controller which should be used by the controls in the Fragment. Note that some Fragments may not need a Controller and other may need one - and even rely on certain methods implemented in the Controller. |
{sap.ui.core.Control|sap.ui.core.Control[]} | the root Control(s) of the Fragment content |
{sap.ui.core.Core} | the API of the current SAPUI5 Core instance. |
In case of the version info file is not available an error will occur when calling this function.
{string|object} | mOptions? | name of the library (e.g. "sap.ui.core") or a object map (see below) |
{boolean} | mOptions.library? | name of the library (e.g. "sap.ui.core") |
{boolean} | mOptions.async? | whether "sap-ui-version.json" should be loaded asynchronously |
{boolean} | mOptions.failOnError?, Default: true | whether to propagate load errors or not (not relevant for async loading) |
{object|undefined|Promise} | the full version info, the library specific one, undefined (if library is not listed or there was an error and "failOnError" is set to "false") or a Promise which resolves with one of them |
To instantiate a Fragment, call this method as: sap.ui.htmlfragment([sId], sFragmentName, [oController]); The Fragment instance ID is optional (generated if not given) and will be used as prefix for the ID of all contained controls. The sFragmentName must correspond to an HTML Fragment which can be loaded via the module system (fragmentName + ".fragment.html") and which defines the Fragment. If oController is given, the methods referenced in the Fragment will be called on this controller. Note that Fragments may require a Controller to be given and certain methods to be available.
Advanced usage: To instantiate a Fragment and optionally directly give the HTML definition instead of loading it from a file, call this method as: sap.ui.htmlfragment(oFragmentConfig, [oController]); The oFragmentConfig object can have a either a "fragmentName" or a "fragmentContent" property. fragmentContent is optional and can hold the Fragment definition as XML string; if not given, fragmentName must be given and the Fragment content definition is loaded by the module system. Again, if oController is given, the methods referenced in the Fragment will be called on this controller.
{string} | sId? | id of the newly created Fragment |
{string|object} | vFragment | name of the Fragment (or Fragment configuration as described above, in this case no sId may be given. Instead give the id inside the config object, if desired.) |
{sap.ui.core.mvc.Controller} | oController? | a Controller to be used for event handlers in the Fragment |
{sap.ui.core.Control|sap.ui.core.Control[]} | the root Control(s) of the created Fragment instance |
The behavior of this method depends on the signature of the call and on the current context.
- View Definition
sap.ui.htmlview(sId, vView)
: Defines a view of the given name with the given implementation. sId must be the views name, vView must be an object and can contain implementations for any of the hooks provided by HTMLView - View Instantiation
sap.ui.htmlview(sId?, vView)
: Creates an instance of the view with the given name (and id) .
Any other call signature will lead to a runtime error. If the id is omitted in the second variant, an id will be created automatically.
{string} | sId? | id of the newly created view, only allowed for instance creation |
{string|object} | vView | name or implementation of the view. |
{boolean} | vView.async? | defines how the view source is loaded and rendered later on |
{sap.ui.core.mvc.HTMLView|undefined} | the created HTMLView instance in the creation case, otherwise undefined |
To define a JS Fragment, call this method as: sap.ui.jsfragment(sName, oFragmentDefinition) Where: - "sName" is the name by which this fragment can be found and instantiated. If defined in its own file, in order to be found by the module loading system, the file location and name must correspond to sName (path + file name must be: fragmentName + ".fragment.js"). - "oFragmentDefinition" is an object at least holding the "createContent(oController)" method which defines the Fragment content. If given during instantiation, the createContent method receives a Controller instance (otherwise oController is undefined) and the return value must be one sap.ui.core.Control (which could have any number of children).
To instantiate a JS Fragment, call this method as: sap.ui.jsfragment([sId], sFragmentName, [oController]); The Fragment ID is optional (generated if not given) and the Fragment implementation CAN use it to make contained controls unique (this depends on the implementation: some JS Fragments may choose not to support multiple instances within one application and not use the ID prefixing). The sFragmentName must correspond to a JS Fragment which can be loaded via the module system (fragmentName + ".fragment.js") and which defines the Fragment. If oController is given, the methods referenced in the Fragment will be called on this controller. Note that Fragments may require a Controller to be given and certain methods to be available.
{string} | sId? | id of the newly created Fragment |
{string|object} | sFragmentName | name of the Fragment (or Fragment configuration as described above, in this case no sId may be given. Instead give the id inside the config object, if desired) |
{sap.ui.core.mvc.Controller} | oController? | a Controller to be used for event handlers in the Fragment |
{sap.ui.core.Control|sap.ui.core.Control[]} | the root Control(s) of the created Fragment instance |
The viewName
must either correspond to a JSON module that can be loaded via the module system (viewName + suffix ".view.json") and which defines the view or it must be a configuration object for a view. The configuration object can have a viewName, viewContent and a controller property. The viewName behaves as described above, viewContent can hold the view description as JSON string or as object literal.
Note: when an object literal is given, it might be modified during view construction.
The controller property can hold an controller instance. If a controller instance is given, it overrides the controller defined in the view.
Like with any other control, an id is optional and will be created when missing.
{string} | sId? | id of the newly created view |
{string|object} | vView | name of a view resource or view configuration as described above. |
{string} | vView.viewName? | name of a view resource in module name notation (without suffix) |
{string|object} | vView.viewContent? | view definition as a JSON string or an object literal |
{boolean} | vView.async? | defines how the view source is loaded and rendered later on |
{sap.ui.core.mvc.Controller} | vView.controller? | controller to be used for this view instance |
{sap.ui.core.mvc.JSONView} | the created JSONView instance |
The behavior of this method depends on the signature of the call and on the current context.
- View Definition
sap.ui.jsview(sId, vView)
: Defines a view of the given name with the given implementation. sId must be the view's name, vView must be an object and can contain implementations for any of the hooks provided by JSView - View Instantiation
sap.ui.jsview(sId?, vView)
: Creates an instance of the view with the given name (and id). If no view implementation has been defined for that view name, a JavaScript module with the same name and with suffix "view.js" will be loaded and executed. The module should contain a view definition (1st. variant above).
Any other call signature will lead to a runtime error. If the id is omitted in the second variant, an id will be created automatically.
{string} | sId? | id of the newly created view, only allowed for instance creation |
{string|object} | vView | name or implementation of the view. |
{boolean} | bAsync? | defines how the view source is loaded and rendered later on (only relevant for instantiation, ignored for everything else) |
{sap.ui.core.mvc.JSView|undefined} | the created JSView instance in the creation case, otherwise undefined |
sClassName
. If the class has been loaded already, nothing is done. Otherwise a stub object or constructor and - optionally - a set of stub methods are created. All created stubs will load the corresponding module on execution and then delegate to their counterpart in the loaded module.
When no methods are given or when the list of methods contains the special name "new" (which is an operator can't be used as method name in JavaScript), then a stub constructor for class sClassName
is created. Otherwise, a plain object is created.
Note: Accessing any stub as a plain object without executing it (no matter whether it is a function or an object) won't load the module and therefore most like won't work as expected. This is a fundamental restriction of the lazy loader approach. It could only be fixed with JavaScript 1.5 features that are not available in all UI5 target browsers (e.g. not in IE8).
Note: As a side effect of this method, the namespace containing the given class is created immediately.
{string} | sClassName | Fully qualified name (dot notation) of the class that should be prepared |
{string} | sMethods?, Default: 'new' | space separated list of additional (static) methods that should be created as stubs |
{string} | sModuleName? | name of the module to load, defaults to the class name |
Any UI5 managed resource (view, controller, control, JavaScript module, CSS file, etc.) whose resource name starts with sNamespace
, will be loaded from an equally named subfolder of the application root folder. If the resource name consists of multiple segments (separated by a dot), each segment is assumed to represent an individual folder. In other words: when a resource name is converted to an URL, any dots ('.') are converted to slashes ('/').
Limitation: For the time being, the application root folder is assumed to be the same as the folder where the current page resides in.
Usage sample:
// Let UI5 know that resources, whose name starts with "com.mycompany.myapp" // should be loaded from the URL location "./com/mycompany/myapp" sap.ui.localResources("com.mycompany.myapp"); // The following call implicitly will use the mapping done by the previous line // It will load a view from ./com/mycompany/myapp/views/Main.view.xml sap.ui.view({ view : "com.mycompany.myapp.views.Main", type : sap.ui.core.mvc.ViewType.XML});
When applications need a more flexible mapping between resource names and their location, they can use jQuery.sap.registerModulePath.
It is intended to make this configuration obsolete in future releases, but for the time being, applications must call this method when they want to store resources relative to the assumed application root folder.
{string} | sNamespace | Namespace prefix for which to load resources relative to the application root folder |
jQuery.sap.registerModulePath |
Synchronous Retrieval of a Single Module Value
When called with a single string, that string is assumed to be the name of an already loaded module and the value of that module is returned. If the module has not been loaded yet, or if it is a Non-UI5 module (e.g. third party module), undefined
is returned. This signature variant allows synchronous access to module values without initiating module loading.
Sample:
var JSONModel = sap.ui.require("sap/ui/model/json/JSONModel");
For modules that are known to be UI5 modules, this signature variant can be used to check whether the module has been loaded.
Asynchronous Loading of Multiple Modules
If an array of strings is given and (optionally) a callback function, then the strings are interpreted as module names and the corresponding modules (and their transitive dependencies) are loaded. Then the callback function will be called asynchronously. The module values of the specified modules will be provided as parameters to the callback function in the same order in which they appeared in the dependencies array.
The return value for the asynchronous use case is undefined
.
sap.ui.require(['sap/ui/model/json/JSONModel', 'sap/ui/core/UIComponent'], function(JSONModel,UIComponent) { var MyComponent = UIComponent.extend('MyComponent', { ... }); ... });
This method uses the same variation of the unified resource name syntax that sap.ui.define uses: module names are specified without the implicit extension '.js'. Relative module names are not supported.
Experimental API:Since 1.27.0 - not all aspects of sap.ui.require are settled yet. E.g. the return value of the asynchronous use case might change (currently it is undefined).
{string|string[]} | vDependencies | dependency (dependencies) to resolve |
{function} | fnCallback? | callback function to execute after resolving an array of dependencies |
- Experimental:
- Since 1.27.0 - not all aspects of sap.ui.require are settled yet. E.g. the return value of the asynchronous use case might change (currently it is undefined).
{any|undefined} | a single module value or undefined |
{string} | sLibraryName | the name of a library, like "sap.ui.commons" |
{string} | sResourcePath | the relative path of a resource inside this library, like "img/mypic.png" or "themes/my_theme/img/mypic.png" |
{string} | the URL of the requested resource |
Template
instance. If you want to lookup all kind of existing and known templates and parse them directly you can simply call:
sap.ui.template();
To parse a concrete DOM element you can do so by using this function in the following way:
sap.ui.template("theTemplateId");
Or you can pass the reference to a DOM element and use this DOM element as a source for the template:
sap.ui.template(oDomRef);
The last option to use this function is to pass the information via a configuration object. This configuration object can be used to pass a context for the templating framework when compiling the template:
var oTemplateById = sap.ui.template({ id: "theTemplateId", context: { ... } }); var oTemplateByDomRef = sap.ui.template({ domref: oDomRef, context: { ... } });
It can also be used to load a template from another file:
var oTemplate = sap.ui.template({ id: "myTemplate", src: "myTemplate.tmpl" }); var oTemplateWithContext = sap.ui.template({ id: "myTemplate", src: "myTemplate.tmpl", context: { ... } });
The properties of the configuration object are the following:
id
- the ID of the Template / the ID of the DOM element containing the source of the Templatedomref
- the DOM element containing the source of the Templatetype
- the type of the Templatesrc
- the URL to lookup the template (experimental!) control
- the fully qualified name of the control to declare (experimental!)
{string|DomRef|object} | oTemplate? | the id or the DOM reference to the template to lookup or an configuration object containing the src, type and eventually the id of the Template. |
{sap.ui.core.tmpl.Template|sap.ui.core.tmpl.Template[]} | the created Template instance or in case of usage without parametes any array of templates is returned |
The behavior of this method depends on the signature of the call and on the current context.
- View Definition
sap.ui.templateview(sId, vView)
: Defines a view of the given name with the given implementation. sId must be the views name, vView must be an object and can contain implementations for any of the hooks provided by templateview - View Instantiation
sap.ui.templateview(sId?, vView)
: Creates an instance of the view with the given name (and id) .
Any other call signature will lead to a runtime error. If the id is omitted in the second variant, an id will be created automatically.
{string} | sId? | id of the newly created view, only allowed for instance creation |
{string|object} | vView | name or implementation of the view. |
{sap.ui.core.mvc.TemplateView|undefined} | the created TemplateView instance in the creation case, otherwise undefined |
The vView
configuration object can have the following properties for the view instantiation:
- The ID
vView.id
specifies an ID for the View instance. If no ID is given, an ID will be generated. - The view name
vView.viewName
corresponds to an XML module that can be loaded via the module system (vView.viewName + suffix ".view.xml") - The controller instance
vView.controller
must be a valid controller implementation. The given controller instance overrides the controller defined in the view definition - The view type
vView.type
specifies what kind of view will be instantiated. All valid view types are listed in the enumeration sap.ui.core.mvc.ViewType. - The view data
vView.viewData
can hold user specific data. This data is available during the whole lifecycle of the view and the controller - The view loading mode
vView.async
must be a boolean and defines if the view source is loaded synchronously or asynchronously. In async mode, the view is rendered empty initially, and rerenderd with the loaded view content. vView.preprocessors
can hold a map from the specified preprocessor type (e.g. "xml") to an array of preprocessor configurations; each configuration consists of a
preprocessor
property (optional when registered as on-demand preprocessor) and may contain further preprocessor-specific settings. The preprocessor can be either a module name as string implementation of sap.ui.core.mvc.View.Preprocessor or a function according to sap.ui.core.mvc.View.Preprocessor.process. Do not set properties starting with underscore like _sProperty
property, these are reserved for internal purposes. When several preprocessors are provided for one hook, it has to be made sure that they do not conflict when beeing processed serially. Note: These preprocessors are only available to this instance. For global or on-demand availability use sap.ui.core.mvc.XMLView.registerPreprocessor.
Note: Please note that preprocessors in general are currently only available to XMLViews.
Note: Preprocessors only work in async views and will be ignored when the view is instantiated in sync mode by default, as this could have unexpected side effects. You may override this behaviour by setting the bSyncSupport flag of the preprocessor to true.
{string} | sId | id of the newly created view, only allowed for instance creation |
{string|object} | vView? | the view name or view configuration object |
{boolean} | vView.async? | defines how the view source is loaded and rendered later on |
{sap.ui.core.mvc.View} | the created View instance |
To instantiate a Fragment, call this method as: sap.ui.xmlfragment([sId], sFragmentName, [oController]); The Fragment instance ID is optional (generated if not given) and will be used as prefix for the ID of all contained controls. The sFragmentName must correspond to an XML Fragment which can be loaded via the module system (fragmentName + ".fragment.xml") and which defines the Fragment. If oController is given, the methods referenced in the Fragment will be called on this controller. Note that Fragments may require a Controller to be given and certain methods to be available.
Advanced usage: To instantiate a Fragment and optionally directly give the XML definition instead of loading it from a file, call this method as: sap.ui.xmlfragment(oFragmentConfig, [oController]); The oFragmentConfig object can have a either a "fragmentName" or a "fragmentContent" property. fragmentContent is optional and can hold the Fragment definition as XML string; if not given, fragmentName must be given and the Fragment content definition is loaded by the module system. Again, if oController is given, the methods referenced in the Fragment will be called on this controller.
{string} | sId? | id of the newly created Fragment |
{string|object} | vFragment | name of the Fragment (or Fragment configuration as described above, in this case no sId may be given. Instead give the id inside the config object, if desired) |
{sap.ui.core.mvc.Controller} | oController? | a Controller to be used for event handlers in the Fragment |
{sap.ui.core.Control|sap.ui.core.Control[]} | the root Control(s) of the created Fragment instance |
The viewName
must either correspond to an XML module that can be loaded via the module system (viewName + suffix ".view.xml") and which defines the view or it must be a configuration object for a view. The configuration object can have a viewName, viewContent and a controller property. The viewName behaves as described above. ViewContent is optional and can hold a view description as XML string or as already parsed XML Document. If not given, the view content definition is loaded by the module system.
Note: if a Document is given, it might be modified during view construction.
The controller property can hold an controller instance. If a controller instance is given, it overrides the controller defined in the view.
Like with any other control, id is optional and one will be created automatically.
{string} | sId? | id of the newly created view |
{string|object} | vView | name of the view or a view configuration object as described above. |
{string} | vView.viewName? | name of the view resource in module name notation (without suffix) |
{string|Document} | vView.viewContent? | XML string or XML document that defines the view. |
{boolean} | vView.async? | defines how the view source is loaded and rendered later on |
{sap.ui.core.mvc.Controller} | vView.controller? | Controller instance to be used for this view |
{sap.ui.core.mvc.XMLView} | the created XMLView instance |
window
. {string} | sNamespace |
- Deprecated:
- Use jQuery.sap.declare or jQuery.sap.getObject(...,0) instead
{object} | the innermost namespace of the hierarchy |
Example:
<div id="SAPUI5UiArea"></div> <script type="text/javascript"> var oRoot = new sap.ui.commons.Label(); oRoot.setText("Hello world!"); sap.ui.setRoot("SAPUI5UiArea", oRoot); </script>
This is a shortcut for sap.ui.getCore().setRoot()
.
Internally, if a string is given that does not identify an UIArea or a control then implicitly a new UIArea
is created for the given DOM reference and the given control is added.
{string|Element|sap.ui.core.Control} | oDomRef | a DOM Element or Id String of the UIArea |
{sap.ui.base.Interface|sap.ui.core.Control} | oControl | the Control that should be added to the UIArea . |
- Deprecated:
- Use function
placeAt
ofsap.ui.core.Control
instead.