Is there a way of composing a template in Lit using a dynamically derived Lit Element?
I'm talking something like this:
import { chooseCorrectComponent } from "./chooseCorrectComponent.js";
let myLitElement = chooseCorrectComponent(arguments);
render () {
return html`
${new myLitElement(propsGoHerePerhaps)}
`
}
Was easier than I thought.
function chooseCorrectCoupon(arg) {
if(arg === "foo") {
return new MyLitElementA();
} else {
return new MyLitElementB();
}
}
render () {
let myLitElement = chooseCorrectComponent("bar");
myLitElement.propA = 123;
myLitElement.propB = "hello";
return html`
${myLitElement}
`
}
Related
I'm using generator-jhipster and I want to create blueprints for entity-client. After writing entity files, a postWriting function will call addEnitiyToMenu in generator-jhipster/generators/client/needle-api/needle-client-react.js to add new entity generated to file menu/entities.tsx
I need to override this function to write a different entityEntry with original one.
But I can't find the template for it. What should I do?
I found that I can write these function by my own. There is example code if you need
function generateFileModel(aFile, needleTag, ...content) {
return {
file: aFile,
needle: needleTag,
splicable: content,
};
}
function addBlockContentToFile(rewriteFileModel, generator) {
try {
return jhipsterUtils.rewriteFile(rewriteFileModel, generator);
} catch (e) {
console.error(e);
return null;
}
}
function addToMenu() {
if (this.skipClient) return;
if (!this.embedded) {
this.addEntityToModule();
const entityMenuPath = `${this.CLIENT_MAIN_SRC_DIR}app/shared/layout/menus/entities.tsx`;
const entityEntry =
// prettier-ignore
this.stripMargin(`|<Menu.Item key="${this.entityStateName}" icon={<FileOutlined />}>
| <Link to="/${this.entityStateName}">
| ${this.enableTranslation ? `<Translate contentKey="global.menu.entities.${this.entityTranslationKeyMenu}" />` : `${_.startCase(this.entityStateName)}`}
| </Link>
| </Menu.Item>`);
const rewriteFileModel = generateFileModel(entityMenuPath, 'jhipster-needle-add-entity-to-menu', entityEntry);
addBlockContentToFile(rewriteFileModel, this);
}
}
function replaceTranslations() {
if (this.clientFramework === VUE && !this.enableTranslation) {
if (!this.readOnly) {
utils.vueReplaceTranslation(this, [
`app/entities/${this.entityFolderName}/${this.entityFileName}.vue`,
`app/entities/${this.entityFolderName}/${this.entityFileName}-update.vue`,
`app/entities/${this.entityFolderName}/${this.entityFileName}-details.vue`,
]);
} else {
utils.vueReplaceTranslation(this, [
`app/entities/${this.entityFolderName}/${this.entityFileName}.vue`,
`app/entities/${this.entityFolderName}/${this.entityFileName}-details.vue`,
]);
}
}
}
I install a library/module but I am curious how they do it
const modules = require('abc');
const app = new modules('123');
const client = app.f1('abcdef').f2('ghi');
console.log(client.to());
const client2 = app.f1('1111111').f2('2222');
console.log(client2.to());
console.log(client.to());
result is 123:abcdef-ghi
result is 123:1111111-2222
result is 123:abcdef-ghi
how they did it?
i want to create that example lib/module
please give me sample code
Depending on your exact requirements, something like this seems to work:
let state = Symbol("private")
class App {
constructor(arg) {
this[state] = arg
}
f1 = arg => new App(this[state] + ":" + arg)
f2 = arg => new App(this[state] + "-" + arg)
to = () => this[state]
}
Here each of the chainable method returns a new instance of the class, each keeping the temporary result as a local state. The to() method returns that state.
This is what I use for doing function().anotherFunction()
function func() {
console.log("ran func")
return {
"anotherFunc": function () {
console.log("ran another func")
}
}
}
func().anotherFunc()
You can also just return a object
const returnData = {
"anotherFunc": function () {
console.log("ran another func")
}
}
function func() {
console.log("ran func")
return returnData
}
func().anotherFunc()
Example of use:
function word1(in_1) {
return {
"word2": function (in_2) {
console.log(`Inputs: ${in_1} ${in_2}`)
}
}
}
word1("Hello").word2("World")
// Expected output: Inputs: Hello World
I am making a simple note taking app to learn node and ES6. I have 3 modules - App, NotesManager and Note. I am importing the Note class into the NotesManager and am trying to instantiate it in its addNote function. The problem is that even though the import is correct, it turns out to be undefined inside the class definition. A simpler solution would be to just instantiate the NotesManager class and add the Note class to its constructor however, I want to have NotesManager as a static utility class.
Here is my code.
Note.js
class Note {
constructor(title, body) {
this.title = title;
this.body = body;
}
}
module.exports = Note;
NotesManager.js
const note = require("./Note");
console.log("Note: ", note); //shows correctly
class NotesManager {
constructor() {}
static addNote(title, body) {
const note = new note(title, body); //Fails here as note is undefined
NotesManager.notes.push(note);
}
static getNote(title) {
if (title) {
console.log(`Getting Note: ${title}`);
} else {
console.log("Please provide a legit title");
}
}
static removeNote(title) {
if (title) {
console.log(`Removing Note: ${title}`);
} else {
console.log("Please provide a legit title");
}
}
static getAll() {
//console.log("Getting all notes ", NotesManager.notes, note);
}
}
NotesManager.notes = []; //Want notes to be a static variable
module.exports.NotesManager = NotesManager;
App.js
console.log("Starting App");
const fs = require("fs"),
_ = require("lodash"),
yargs = require("yargs"),
{ NotesManager } = require("./NotesManager");
console.log(NotesManager.getAll()); //works
const command = process.argv[2],
argv = yargs.argv;
console.log(argv);
switch (command) {
case "add":
const title = argv.title || "No title given";
const body = argv.body || "";
NotesManager.addNote(title, body); //Fails here
break;
case "list":
NotesManager.getAll();
break;
case "remove":
NotesManager.removeNote(argv.title);
break;
case "read":
NotesManager.getNote(argv.title);
break;
default:
notes.getAll();
break;
}
Is it possible for me to create a strict utility class which I can use without instantiating like in Java? Pretty new here and have tried searching for it without any luck. Thank you for your help.
When you do this:
const note = new note(title, body);
you redefine note shadowing the original note from the outer scope. You need to pick a different variable name.
Something like this should work better:
static addNote(title, body) {
const some_note = new note(title, body); //Fails here as note is undefined
NotesManager.notes.push(some_note);
}
I'm writing a simple React application with a Button component, which looks like this:
import React, { Component } from 'react';
// shim to find stuff
Array.prototype.contains = function (needle) {
for (var i = 0; i < this.length; i++) {
if (this[i] == needle) return true;
}
return false;
};
class Button extends Component {
propTypes: {
text: React.PropTypes.string.isRequired,
modifiers: React.PropTypes.array
}
render() {
return(
<span className={this.displayModifiers()}>{this.props.text}</span>
);
}
displayModifiers() {
const modifiers = this.props.modifiers || ["default"];
if (modifiers.contains("default") ||
modifiers.contains("danger") ||
modifiers.contains("success")) {
// do nothing
} else {
// add default
modifiers.push("defualt");
}
var classNames = "btn"
for (var i = 0; i < modifiers.length; i++) {
classNames += " btn-" + modifiers[i]
}
return(classNames);
}
}
export default Button;
I then wrote this to test it:
it("contains the correct bootstrap classes", () => {
expect(mount(<Button modifiers={["flat"]}/>).html()).toContain("<span class=\"btn btn-flat btn-default\"></span>");
});
That code should pass, but I receive the following error message:
expect(string).toContain(value)
Expected string:
"<span class=\"btn btn-flat btn-defualt\"></span>"
To contain value:
"<span class=\"btn btn-flat btn-default\"></span>"
at Object.it (src\__tests__\Button.test.js:42:293)
Any ideas why this is not passing?
From the docs:
Use .toContain when you want to check that an item is in a list.
To test strings you should use toBe or toEqual
it("contains the correct bootstrap classes", () => {
expect(mount(<Button modifiers={["flat"]}/>).html()).toBe("<span class=\"btn btn-flat btn-default\"></span>");
});
But there is a better way of testing the output rendered components: snapshots.
it("contains the correct bootstrap classes", () => {
expect(mount(<Button modifiers={["flat"]}/>).html()).toMatchSnapshot();
});
Note that you will need enzymeToJson for snapshot testing using enzyme.
Is it possible to mock getter and setter of the property by Mockito? Something like this:
#Test
fun three() {
val m = mock<Ddd>() {
// on { getQq() }.doReturn("mocked!")
}
assertEquals("mocked!", m.qq)
}
open class Ddd {
var qq : String = "start"
set(value) {
field = value + " by setter"
}
get() {
return field + " by getter"
}
}
To mock getter just write:
val m = mock<Ddd>()
`when`(m.qq).thenReturn("42")
also i suggest to use mockito-kotlin, to use useful extensions and functions like whenever:
val m = mock<Ddd>()
whenever(m.qq).thenReturn("42")
Complementing IRus' answer, you could also use the following syntax:
val mockedObj = mock<SomeClass> {
on { funA() } doReturn "valA"
on { funB() } doReturn "valB"
}
or
val mockedObj = mock<SomeClass> {
on(it.funA()).thenReturn("valA")
on(it.funB()).thenReturn("valB")
}