I have a simple interface in Kotlin that looks like this:
interface IMyInterface {
var name: String
var description: String }
With a build.gradle file like this:
apply plugin: 'java'
apply plugin: 'kotlin2js'
sourceCompatibility = 1.8
repositories {
mavenCentral() }
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version"
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" }
compileKotlin2Js {
kotlinOptions.moduleKind = "umd"
kotlinOptions.sourceMap = true }
The javascript that it exports when I build exports this:
(function (root, factory) {
if (typeof define === 'function' && define.amd)
define(['exports', 'kotlin'], factory);
else if (typeof exports === 'object')
factory(module.exports, require('kotlin'));
else {
if (typeof kotlin === 'undefined') {
throw new Error("Error loading module 'myModule'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'myModule'.");
}
root['myModule'] = factory(typeof this['myModule'] === 'undefined' ? {} : this['myModule'], kotlin);
}
}(this, function (_, Kotlin) {
'use strict';
function IMyInterface() {
}
IMyInterface.$metadata$ = {
kind: Kotlin.Kind.INTERFACE,
simpleName: 'IMyInterface',
interfaces: []
};
_.IMyInterface = IMyInterface;
Kotlin.defineModule('myModule', _);
return _;
}));
If you notice that the javascript that is exported does not contain any of the properties that my interface defines (name,description are missing).
What I would like to see is an export along the lines like this:
IMyInterface = function ( args ) {
"use strict";
var _name = "";
Object.defineProperty(this,"name",{
enumerable: true,
get: function() { return _name; },
set: function(value) { _name = value; }
});
var _description = "";
Object.defineProperty(this,"description",{
enumerable: true,
get: function() { return _description; },
set: function(value) { _description = value; }
});
Also I am using kotlin version 1.1.51
Thank you!
Related
I want to divide an app in a TypeScript development environment into function files - so that each file contains only one function.
I would like to realise this with TS modules. In the compiled JavaScript file, however, these modules should not get imported at runtime, but compiled as native code.
For example, from this app.ts
type ArbitraryAttribute = any //can refer to any value valid at runtime
declare interface App {
get? (key: string): ArbitraryAttribute | void,
set? (key: string, val: ArbitraryAttribute): void,
helper?: AppHelper,
}
declare interface AppHelper {
deepGetter? (key: string): ArbitraryAttribute | void,
deepSetter? (key: string, val: ArbitraryAttribute): void,
}
import { get } from "./get";
import { set } from "./set";
import { helper } from "./helper/index";
const app:App = {
get,
set,
helper,
}
this app.js is to be generated:
var app = {
get: function (key) {
if (app.helper && app.helper.deepGetter) {
return app.helper.deepGetter(key);
};
},
set: function (key, val) {
if (app.helper && app.helper.deepSetter) {
app.helper.deepSetter(key, val);
};
},
helper: {
deepGetter: function (key) {
// get anything
},
deepSetter: function (key, val) {
// set anything
},
},
};
Neither in the TypeScript configuration nor in webpack have I found a solution for this.
This should be feasible, right? Does anyone know a solution or a library that solves this problem?
As #Dimava mentions, via tsconfig there is the possibility to merge a number of typescript files into a single js file, but the result for my aproach is really messy. The previosly postet js file will look like this:
System.register("get", [], function (exports_1, context_1) {
"use strict";
var get;
var __moduleName = context_1 && context_1.id;
return {
setters: [],
execute: function () {
exports_1("get", get = function (key) {
if (app.helper && app.helper.deepGetter) {
return app.helper.deepGetter(key);
}
;
});
}
};
});
System.register("set", [], function (exports_2, context_2) {
"use strict";
var set;
var __moduleName = context_2 && context_2.id;
return {
setters: [],
execute: function () {
exports_2("set", set = function (key, val) {
if (app.helper && app.helper.deepSetter) {
return app.helper.deepSetter(key, val);
}
});
}
};
});
System.register("helper/deepGetter", [], function (exports_3, context_3) {
"use strict";
var deepGetter;
var __moduleName = context_3 && context_3.id;
return {
setters: [],
execute: function () {
exports_3("deepGetter", deepGetter = function (key) {
// get anything
});
}
};
});
System.register("helper/deepSetter", [], function (exports_4, context_4) {
"use strict";
var deepSetter;
var __moduleName = context_4 && context_4.id;
return {
setters: [],
execute: function () {
exports_4("deepSetter", deepSetter = function (key, val) {
// set anything
});
}
};
});
System.register("helper/index", ["helper/deepGetter", "helper/deepSetter"], function (exports_5, context_5) {
"use strict";
var deepGetter_1, deepSetter_1, helper;
var __moduleName = context_5 && context_5.id;
return {
setters: [
function (deepGetter_1_1) {
deepGetter_1 = deepGetter_1_1;
},
function (deepSetter_1_1) {
deepSetter_1 = deepSetter_1_1;
}
],
execute: function () {
exports_5("helper", helper = {
deepGetter: deepGetter_1.deepGetter,
deepSetter: deepSetter_1.deepSetter,
});
}
};
});
System.register("index", ["get", "set", "helper/index"], function (exports_6, context_6) {
"use strict";
var get_1, set_1, index_1, app;
var __moduleName = context_6 && context_6.id;
return {
setters: [
function (get_1_1) {
get_1 = get_1_1;
},
function (set_1_1) {
set_1 = set_1_1;
},
function (index_1_1) {
index_1 = index_1_1;
}
],
execute: function () {
app = {
get: get_1.get,
set: set_1.set,
helper: index_1.helper,
};
}
};
});
I haven't get it working for "--module es2015 --moduleResolution classic",
only for for "--module system --moduleResolution node".
And the file weighs almost six and a half times as much!
working currently with a code base that I'm not familiar with and I'm trying to instantiate some comparison operators with Handlebars.js that's already in place. Where can I add this registerHelper to the JS file?
Helper I need to register:
Handlebars.registerHelper('ifCond', function(v1, v2, options) {
if(v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
});
Area I think I need to put it?
function HandlebarsEnvironment(helpers, partials, decorators) {
this.helpers = helpers || {};
this.partials = partials || {};
this.decorators = decorators || {};
_helpers.registerDefaultHelpers(this);
_decorators.registerDefaultDecorators(this);
}
HandlebarsEnvironment.prototype = {
constructor: HandlebarsEnvironment,
logger: _logger2['default'],
log: _logger2['default'].log,
registerHelper: function registerHelper(name, fn) {
if (_utils.toString.call(name) === objectType) {
if (fn) {
throw new _exception2['default']('Arg not supported with multiple helpers');
}
_utils.extend(this.helpers, name);
} else {
this.helpers[name] = fn;
}
},
unregisterHelper: function unregisterHelper(name) {
delete this.helpers[name];
},
registerPartial: function registerPartial(name, partial) {
if (_utils.toString.call(name) === objectType) {
_utils.extend(this.partials, name);
} else {
if (typeof partial === 'undefined') {
throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined');
}
this.partials[name] = partial;
}
},
unregisterPartial: function unregisterPartial(name) {
delete this.partials[name];
},
Thanks for your help.
I am build my project using vite babel typescript and dynamic import
Dev build is working fine
But production build had some strange problem
I see that some function named _interopRequireWildcard calls the function _typeofB
_typeofB - not callable, but they have a default method
_typeofB = {
default: ƒ _typeofA(obj)
__esModule: true
}
What configuration property can affect this?
i.e. bundle code with error:
import {a7 as getAugmentedNamespace, a8 as _typeofA, ...} from './vendor.js';
var requireA = /*#__PURE__*/getAugmentedNamespace(_typeofA);
var _typeofB = requireA;
function _interopRequireWildcard(obj, nodeInterop) {
if (obj === null || _typeofB(obj) !== "object" && typeof obj !== "function") {
^^^^^^^^ - _typeofB is not a function
return {
"default": obj
};
}
...
}
That works if I manually add:
if (obj === null || _typeofB["default"](obj) !== "object" && typeof obj !== "function") {
^^^^^^^^^^^
Is it possible to have a singleton Angular service with getters and setters with logic? I was given the following snippet and asked to mimic it in an Angular service. It may sound simple but I'm losing my mind:
public class Profile
{
private AuthSvc _auth = new AuthSvc();
private string _userId = null;
private string _displayName = null;
public string UserId
{
get
{
if (_userId != null) { return _userId; }
_userId = AuthSvc.getUserId();
return _userId;
}
}
public string DisplayName
{
get
{
if (_displayName != null) { return _displayName; }
if (_userId == null) { return null; }
_displayName = AuthSvc.getDisplayName(_userId);
return _displayName;
}
set (string value) {
if (value == null && value.trim().length < 1) { return; }
if (_displayName != null && _displayName == value.trim()) { return; }
_displayName = value.trim();
AuthSvc.setDisplayName(_userId, _displayName);
}
}
}
My failed attempt before I started crying:
(function () {
'use strict';
angular
.module('myapp')
.service('Profile', ProfileService);
ProfileService.$inject = ['common', 'dataService'];
function ProfileService (common, dataService) {
var userInfo = {
id : '',
name : ''
};
var service = {
id : $get getUserId(),
name : $get getUserId(), $set(value, setUserId);
};
return service;
/////////////////////////
function getUserId () {
if (!userInfo.id) { userInfo.id = common.getUserId(); }
return userInfo.id;
}
function setName (value) {
}
function getName () {
if (userInfo.name) { return userInfo.name; }
var userId = getUserId();
if (!userId) { return ''; }
dataService.users.getDisplayName(userId).then(function(name){
});
}
}
})();
You have written the service as a factory.
An angular service is a constructor that uses this for all properties and a factory is a function that returns an object
You should be fine switching the component from service to factory
angular
.module('myapp')
.factory('Profile', ProfileService);
But you should also be passing function and object variable references to the returned object also
Along the lines of:
var service = {
userInfo : userInfo ,
getUserId : getUserId,
getName : getName
};
// or
service.myfunc = someNamedFunction;
Alternatively keeping it as as service switch all variables to be members of this
Actually service is just a plain object and you can use Object.defineProperty on it. I use factory syntax.
(function () {
'use strict';
angular.module('mymodule', [])
.factory('myService', function () {
var service = {};
var userInfo = {
id : '',
name : ''
};
serivce.getUserInfo = function(){ return userInfo;};
var myPropertyPrivateVal;
Object.defineProperty(service, 'myProperty', {
get: function () { return myPropertyPrivateVal; },
set: function(value) { myPropertyPrivateVal = value; }
});
return service;
});
})();
And you are good to go :)
All the dirrefece when you use service syntax is that you use this instead of an object literal var service = {};
(function () {
'use strict';
angular.module('mymodule', [])
.service('myService', function () {
var userInfo = {id : '', name : '' };
this.getUserInfo = function(){ return userInfo;};
var myPropertyPrivateVal;
Object.defineProperty(this, 'myProperty', {
get: function () { return myPropertyPrivateVal; },
set: function(value) { myPropertyPrivateVal = value; }
});
});
})();
I'm trying to test a requirejs module that has two dependencies (jquery and another custom module).
myModule-Test.js
'use strict';
(function() {
var uut,
modulePath= "../../main/webapp/js/modules/myModule.js";
module("myModule object test suite", {
setup: function() {
QUnit.stop();
require.config({
map: {
"*": {
"jquery": "../../main/webapp/js/jquery/jquery-1.11.0.min.js",
"screenLabelsResolver": "../../main/webapp/js/modules/my-screen-labels-resolver"
}
}
});
require([modulePath], function(module) {
uut = module;
QUnit.start();
});
},
teardown: function() {
require.undef(modulePath);
require.config({
map: {
"*": {
"jquery": "jquery",
"screenLabelsResolver": "../../main/webapp/js/modules/my-screen-labels-resolver"
}
}
});
}
});
test("Given A Page I Expect The Global myModule Object To Exist", function() {
ok( uut !== undefined );
});
}());
I am using require.config to pass in the dependencies with stop() and a Start().
myModule.js
'use strict';
define(["jquery", "screenLabelsResolver"], function($, screenLabelsResolver) {
var metaTag = $("meta[name='application-name']"),
currentBrand = metaTag.attr("data-brand"),
currentWidth,
viewState,
sessionTimeoutValue = metaTag.attr("data-sessiontimeoutvalue"),
sessionTimeoutWarningValue = metaTag.attr("data-sessiontimeoutwarningvalue"),
screenLabels = {},
perceptionDate = metaTag.attr("data-todayatmidnight"),
currentViewportWidth = $(window).width(),
isViewState = metaTag.attr("data-isviewstate"),
isTouch = $("html").hasClass("touch")
return {
metaTag: function () {
return metaTag;
},
currentBrand: function(){
return currentBrand;
},
currentViewportWidth: function(){
return currentViewportWidth;
},
isViewState: function(){
return isViewState;
},
sessionTimeoutValue: function(){
return sessionTimeoutValue;
},
sessionTimeoutWarningValue: function(){
return sessionTimeoutWarningValue;
},
getPerceptionDate: function(){
return perceptionDate;
},
getOrientation: function () {
return ( window.orientation == -90 || window.orientation == 90 ) ? "landscape" : "portrait";
},
isTouch: function(){
return isTouch;
},
screenLabels: function() {
if (screenLabels = {}) {
screenLabels = screenLabelsResolver( metaTag.attr("data-viewstate") /* or however you want to get the current viewstate name */ );
}
return screenLabels;
}
};
});
I get the error "Uncaught TypeError: undefined is not a function" where I try to use jQuery ($) in line var metaTag = $("meta[name='application-name']").
Somehow, jQuery is not loaded properly by the time the call is made.
My question that is this the correct approach to test r.js modules with multiple dependencies? If so what's the fundamental error in the above code?
Many Thanks in advance.