Where to register Handlebars Helper? - javascript

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.

Related

LIVR Validate if element in object is empty array

I have LIVR in a project i'm working now and is quite unclear to me how this work. I can't understand how to create new rules for custom validation.
Here's the code:
LIVR.Validator.defaultAutoTrim(true);
let validator = new LIVR.Validator({});
LIVR.Validator.registerDefaultRules({
nested_object_value() {
return function (value) {
if (!value || (value && !value.value || value === [])) {
return 'REQUIRED';
}
return '';
};
},
max_number_advancement() {
return function (value) {
if (value > 100) {
return 'MAX_NUMBER';
}
return '';
};
},
required_if_activity_present() {
return function (value, allValue) {
if (allValue.activitycycletype && !value || allValue.requestpeople === []) {
console.log(first)
return 'REQUIRED_IF_CYCLETYPE';
}
return '';
};
},
});
And this is how its used:
validationForm = () => {
const { formValue, updateErrors } = this.props;
const validData = validator.validate(formValue);
console.log(formValue)
if (!validData) {
const errorsValidator = validator.getErrors();
if (errorsValidator && Object.keys(errorsValidator).length > 0) {
const newErrors = {};
Object.keys(errorsValidator).forEach((error) => {
newErrors[error] = errorsValidator[error];
});
updateErrors(newErrors);
}
blame(t('validation-error'));
return false;
}
updateErrors({});
return true;
}
Opening the form with this validation in the app, seems to call only the last method required_if_activity_present().
What i expect here is that i can create a new method inside registerDefaultRules(), that is a LIVR method, like this:
LIVR.Validator.registerDefaultRules({
re quired_not_empty() {
return function (value) {
if (!value) {
return 'REQUIRED';
}
return '';
};
},
... //other methods
}
but seems not working, the newer method is not being called at all by validator.validate()
Anyone know how to create a new rules where i can check if an element inside the object that has to be validate is an empty array?
Because seems that LIVR doesn't return a validation error in this case, but only on empty string and null values.
Thanks in advance

Javascript variable as function name

const self = {
element: document.querySelector(selector),
html: () => self.element,
on: (event, callback) => {
self.element.addEventListener(event, callback);
},
style: {
alignContent: (property) => {
return (property === null) ? self.element.style.alignContent : self.element.style.alignContent = property;
}
}
}
I am trying to make it so I have quick access to all CSS style properties with jQuery like selectors it should work as: select('h1').style.alignContent('center'), but the problem is that I would have to make a seperate function for each style property in order for this method to work, is there a way to solve this problem without duplicating a lot of code?
//Duplication example
color: (property) => {
return (property === null) ? self.element.style.color : self.element.style.color = property;
}
One way to do this is with a Proxy (mdn):
let elemWrapper = selector => {
let element = document.querySelector(selector);
return {
element,
html: () => element,
on: (event, callback) => {
element.addEventListener(event, callback);
},
style: new Proxy({}, {
get: (obj, prop) => {
// The user called a function named "prop"
// We need to return a function that sets the style property named "prop"
return cssValue => element.style[prop] = cssValue;
}
})
};
};
let bodyElem = elemWrapper('body');
bodyElem.style.backgroundColor('cyan');
Here to prove the concept I've set the body element's background colour using a dynamically named function.
The big downside to this approach is the poor performance of Proxies (an excellent read on Proxy performance is available here).
This means it may be quicker to simply compile a list of all css property names, and define a function for each (never using Proxies). The following code compiles all css property names, to serve as a starting point:
console.log(Object.keys(document.body.style));
You can use a Proxy to intercept all attempts to get a property.
let selector = '#test';
const self = {
element: document.querySelector(selector),
html: () => self.element,
on: (event, callback) => {
self.element.addEventListener(event, callback);
},
style: new Proxy(Object.create(null), {
get(target, prop, receiver) {
if (self.element.style.hasOwnProperty(prop)) {
return val => {
if (val != null) {
self.element.style[prop] = val;
} else {
return self.element.style[prop];
}
}
}
throw Error("No such property exists: " + prop);
}
})
};
self.style.color('red')
console.log("Color:", self.style.color());
<div id="test">
This is a test
</div>
You can also wrap this into a general function like so:
const getEnhancedElement = arg => {
const element = /Element/.test(Object.prototype.toString.call(arg)) ? arg
: document.querySelector(arg);//accept a HTMLElement or a selector
return {
element,
html: () => element,
on: (event, callback) => {
element.addEventListener(event, callback);
},
style: new Proxy(Object.create(null), {
get(target, prop) {
if (element.style.hasOwnProperty(prop)) {
return val => {
if (val != null) {//set value
element.style[prop] = val;
} else {//get value
return element.style[prop];
}
}
}
throw Error("No such property exists: " + prop);
}
})
};
};
let test = getEnhancedElement("#test");
test.style.color('red')
console.log("Color:", test.style.color());
test.style.textAlign('center');
<div id="test">
This is a test
</div>
I would have something like this:
style: {
chnageStyle: (propertyName, propertyVal) => {
return (propertyName === null) ? self.element.style[propertyName] : self.element.style[propertyName] = propertyVal;
}
}
Then you can call this:
style.changeStyle('alignContent','center');
style.changeStyle('color','orange');

Ember 1.13 upgradation

I'm upgrading the code from Ember 1.0.4 to Ember 1.13. When I'm execute the below code using ember 1.13 I'm getting the error
title: Ember.computed('content.title', 'managedObject.isHome', 'managedObject.finalManagedObject', {
set: function(name, value) {
this.set('content.title', value);
},
if (this.get('content.title') !== undefined) {
return title;
}
if (this.get('managedObject') == Core.rootNode) {
return "Home";
}
get: function() {
return this.get('managedObject.label') || this.get('managedObject.finalManagedObject.displayName');
}
}),
I'm getting the below error while execute the code.
Uncaught SyntaxError: Unexpected token this
You are using an object to define a computed property. That object must have a get and may have a set function. Both are present. But you have six additional that aren't valid syntax in object definition. You are trying to construct an object like this:
{
set: function(name, value) {
this.set('content.title', value);
},
if (this.get('content.title') !== undefined) {
return title;
}
if (this.get('managedObject') == RSuite.rootNode) {
return "Home";
}
get: function() {
return this.get('managedObject.label') || this.get('managedObject.finalManagedObject.displayName');
}
}
The valid part of that object is:
{
set: function(name, value) {
this.set('content.title', value);
},
get: function() {
return this.get('managedObject.label') || this.get('managedObject.finalManagedObject.displayName');
}
}
Depending on your babel configuration you might be able to simplify it to:
{
set(name, value) {
this.set('content.title', value);
},
get() {
return this.get('managedObject.label') || this.get('managedObject.finalManagedObject.displayName');
}
}
I hope it's clear now. This has nothing to do with upgrade from Ember 1.0.4 to Ember 1.13 in particular. Please have in mind that Ember 1.13 is very old. 2.0 was released more than three years ago. So I would strongly recommend to continue migration until you reach at least to 2.18.
I got the answer by using the below code:
title: Ember.computed('content.title', 'managedObject', 'managedObject.label', 'managedObject.finalManagedObject.displayName', {
set: function(titleKey, newTitle) {
this.set('content.title', newTitle);
if (newTitle !== undefined) {
return newTitle;
} else if (this.get('managedObject') === Core.rootNode) {
return 'Home';
}
return this.get('managedObject.label') || this.get('managedObject.finalManagedObject.displayName');
},
get: function() {
var title = this.get('content.title');
if (title !== undefined) {
return title;
} else if (this.get('managedObject') === Core.rootNode) {
return 'Home';
}
return this.get('managedObject.label') || this.get('managedObject.finalManagedObject.displayName');
}
}),
Thanks for your suggestions Rinold Simon and jelhan.
I think the this reference is lost. Try replacing your code with the below one,
title: Ember.computed('content.title', 'managedObject.isHome', 'managedObject.finalManagedObject', {
set(name, value) {
this.set('content.title', value);
},
get() {
return this.get('managedObject.label') || this.get('managedObject.finalManagedObject.displayName');
}
if (this.get('content.title') !== undefined) {
return title;
}
if (this.get('managedObject') == RSuite.rootNode) {
return "Home";
}
}),

Kotlin interfaces exporting to Javascript missing properties

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!

How to implement an authenticated es 7 decorator with babel for my js service module

I'm using babel with decorator stage:0 support in my flux fluxible js project, and I want to use an authenticated decorator for my service api modules to check for a valid user session.
Googling around, there seems to be several posts that explain different variations but couldn't find one definitive docs or instructionals.
Here's what I tried so far, I know that my parameters for the authenticated function are incorrect, and not sure if I need to implement a class for my module rather than just using the exports object.
The part that I couldn't find the docs for is how to implement the decorator itself - in this case something that takes the req parameter the decorated function will receive and checking it.
// how do I change this method so that it can be implemented as a decorator
function checkAuthenticated(req) {
if (!req.session || !req.session.username)
{
throw new Error('unauthenticated');
}
}
module.exports = {
#checkAuthenticated
read: function(req, resource, params, serviceConfig, callback) {
//#authenticated decorator should allow me to move this out of this here
//checkAuthenticated(req);
if (resource === 'product.search') {
var keyword = params.text;
if (!keyword || keyword.length === 0) {
return callback('empty param', null);
} else {
searchProducts(keyword, callback);
}
}
}
};
class Http{
#checkAuthenticated
read(req, resource, params, serviceConfig, callback) {
if (resource === 'product.search') {
var keyword = params.text;
if (!keyword || keyword.length === 0) {
return callback('empty param', null);
} else {
this.searchProducts(keyword, callback);
}
}
}
searchProducts(keyword, callback) {
callback(null, 'worked');
}
}
function checkAuthenticated(target, key, descriptor) {
return {
...descriptor,
value: function(){
console.log(arguments);
const req = arguments[0];
if (!req.session || !req.session.username) {
throw new Error('unauthenticated');
}
return descriptor.value.apply(this, arguments);
}
};
}
let h = new Http();
h.read(
{ session: { username: 'user' } },
'product.search',
{ text: 'my keywords' },
null,
function(err, result) {
if (err) return alert(err);
return alert(result);
}
);
See jsbin http://jsbin.com/yebito/edit?js,console,output

Categories