Babel es2015 Arrow Function error - ecmascript-6

I'm using es2015 Arrow functions in a React component that is throwing an error when I declare myfunction() {...}. The error doesn't exist if write it like so myFunction : function () {...}. I do not have any issues compiling with Browserify/Babelify - this only happens with the below example.
import React from 'react';
module.exports = React.createClass({
// render : function () { // <--- this works
render() { // <---- this throws an error
return (
<div>Kaboom.</div>
);
}
});
/* RenderService.js */
require("babel-register")({
plugins: ["transform-react-jsx","transform-es2015-modules-commonjs"]
});
var React = require('react');
var ReactDOMServer = require('react-dom/server');
module.exports = {
renderReport : function (reportId) {
var TestComp = require('./TestCompoennt');
var ReactComponent = React.createFactory(TestComp,'div');
return ReactDOMServer.renderToStaticMarkup(ReactComponent());
}
};
Error: renderApproval() {
^
SyntaxError: Unexpected token (

Maybe you should use a preset-es2015, this plugin includes transform-es2015-shorthand-properties, that one you need to transform this:
var z = function() { return 'z'; };
var x = {
z
}
to this:
var z = function() { return 'z'; };
var x = {
z: z
}
Or in your case
var x = {
z() {
return 'z';
}
}
And also includes:
check-es2015-constants
transform-es2015-arrow-functions
transform-es2015-block-scoped-functions
transform-es2015-block-scoping
transform-es2015-classes
transform-es2015-computed-properties
transform-es2015-destructuring
transform-es2015-for-of
transform-es2015-function-name
transform-es2015-literals
transform-es2015-modules-commonjs
transform-es2015-object-super
transform-es2015-parameters
transform-es2015-shorthand-properties
transform-es2015-spread
transform-es2015-sticky-regex
transform-es2015-template-literals
transform-es2015-typeof-symbol
transform-es2015-unicode-regex
transform-regenerator
Link http://babeljs.io/docs/plugins/preset-es2015/

Related

How call C function in js with render SDL in canvas

I am trying to render in canvas the module that I built with SDL2, but I also need to call functions while the module is running and send data there, according to the examples I found it turns out so:
var Module = {
canvas: (function () {
var canvas = document.getElementById('canvas');
canvas.addEventListener('webglcontextlost', e => {
alert('WebGL context lost. You will need to reload the page.');
e.preventDefault();
}, false);
return canvas;
})(),
};
SSE.onmessage = msg => {
Module.onRuntimeInitialized = () => {
Module.ccall('set_num', null, ['number'], [msg]);
};
}
The function was called once, but I need to call it constantly in the event
make with
override CFLAGS += -std=c11\
-Os\
-sUSE_SDL_TTF=2\
-sUSE_SDL_IMAGE=2\
-sSDL2_IMAGE_FORMATS=["png"]\
-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap']\
-sUSE_SDL=2\
-sWASM=1\
-sASSERTIONS\
--preload-file ./res
C
#ifdef __EMSCRIPTEN__
EMSCRIPTEN_KEEPALIVE
#endif
void set_num(int num) { g_obj->num = num; }

How to call method in symbol without assigning to variable

The following works fine by assigning Symbol to sayHello.
var sayHello = Symbol('method');
const bar = {
[sayHello] () {
console.log('hello')
}
};
bar[sayHello]();
How to trigger the method inside Symbol if as follow
const bar3 = {
[Symbol('method')] () {
console.log('hello')
}
};
const sym = Object.getOwnPropertySymbols(bar3)[0];
bar3[sym]();
See Object.getOwnPropertySymbols documentation.

How to free up memory when saving images inside IndexDB

I have a no of images on page and trying to save it inside IndexDb if it does not exist.
All seems to be working fine and images load up instantly if it exist but looks like browser memory is leaking. It's give some jerk and hang sometime. I m not sure how this can be handle, I have written a directive that looks like this
(function () {
'use strict';
// TODO: replace app with your module name
angular.module('app').directive('imageLocal', imageLocal);
imageLocal.$inject = ['$timeout', '$window', 'config', 'indexDb'];
function imageLocal($timeout, $window, config, indexDb) {
// Usage:
//
// Creates:
//
var directive = {
link: link,
restrict: 'A'
};
return directive;
function link(scope, element, attrs) {
var imageId = attrs.imageLocal;
// Open a transaction to the database
var transaction;
$timeout(function () {
transaction = indexDb.db.transaction(["mystore"], "readwrite");
getImage();
}, 500);
function getImage() {
transaction.objectStore('mystore').get(imageId)
.onsuccess = function (event) {
var imgFile = event.target.result;
if (imgFile == undefined) {
saveToDb(imgFile);
return false;
}
showImage(imgFile);
}
}
function showImage(imgFile) {
console.log('getting');
// Get window.URL object
var url = $window.URL || $window.webkitURL;
// Create and revoke ObjectURL
var imageUrl = url.createObjectURL(imgFile);
element.css({
'background-image': 'url("' + imageUrl + '")',
'background-size': 'cover'
});
}
function saveToDb() {
// Create XHR
var xhr = new XMLHttpRequest(),
blob;
xhr.open("GET", config.remoteServiceName + '/image/' + imageId, true);
// Set the responseType to blob
xhr.responseType = "blob";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
console.log("Image retrieved");
// Blob as response
blob = xhr.response;
console.log("Blob:" + blob);
// Put the received blob into IndexedDB
putInDb(blob);
}
}, false);
// Send XHR
xhr.send();
function putInDb(blob) {
// Open a transaction to the database
transaction = indexDb.db.transaction(["mystore"], "readwrite");
// Put the blob into the database
var request = transaction.objectStore("mystore").add(blob, imageId);
getImage();
request.onsuccess = function (event) {
console.log('saved');
}
};
}
}
}
})();

Uncaught TypeError: Cannot read property 'pageSize' of undefined

Iam trying to apply paging to slickgrid and it shows an error in slick.pager.js as title in console and my code is
var jqxhr = $.getJSON('http://localhost:50305/Service1.svc/json/EmployeeDetails', function (data) {
dataView = new Slick.Data.DataView();
dataView.setItems(data, "EmpId");
dataView.setPagingOptions({ pageSize: 4 });
grid = new Slick.Grid("#teamGrid", dataView.rows, columns, options);
var pager = new Slick.Controls.Pager(dataView, grid, $("#pager"));
dataView.onPagingInfoChanged.subscribe(function (e, pagingInfo) {
alert("hi");
var isLastPage = pagingInfo.pageNum == pagingInfo.totalPages - 1;
var enableAddRow = isLastPage || pagingInfo.pageSize == 0;
var options = grid.getOptions();
if (options.enableAddRow != enableAddRow) {
grid.setOptions({ enableAddRow: enableAddRow });
}
});
dataView.onRowCountChanged.subscribe(function (args) {
grid.updateRowCount();
grid.render();
});
Try this:
dataView.beginUpdate();
dataView.setItems(data, "EmpId");
dataView.endUpdate();
dataView.setPagingOptions({ pageSize: 4 });
grid = new Slick.Grid("#teamGrid", dataView, columns, options);
The code doesn't really even make sense.
The line
var jqxhr = $.getJSON('http://localhost:50305/Service1.svc/json/EmployeeDetails', function (data) {
is not well formed. There should be a function body and a closing brace.
The variable jqxhr is not used anywhere. Why does this line even exist ?
`pagesize=10`
let pagesizealt
if(!this.paginator){
pagesizealt=this.pagesize.toString()
}
else{
pagesizealt=this.paginator.pageSize
}`
u have to check for paginator to initialize after initializtion provide the value of pageSize

Backbone using external js

Hi all I have a site developed in cakephp and I would to integrate backbone on it.
For my scope I would to use external js for backbone to reuse the code.
I have write some lines but I can't append results on my element.
I have tried to print the "el" in this modes:
console.log($(this.el));
console.log(this.el);
console.log(this.$el);
But nothing I can't enter into el to make a simple append!
The container #search-results already exist
This is my main view:
<script type="text/javascript">
var search = {};
search.product = {};
search.product.template = "#results-product-template";
search.product.container = "#search-results";
search.product.defaults = {
id:0,
type:"product",
};
$(function(){
var ProductList = new Search.Collections.Products();
var ProductView = new Search.Views.Product({
// new Search.Collections.Products();
collection:ProductList
,el:$("#search-results")
});
function parseResults () {
var json = {
//my data
}
for (var i = json.products.length - 1; i >= 0; i--) {
ProductList.add([new Search.Models.Product(json.products[i])]);
};
updateResults();
}
function updateResults () {
console.log('updateResults: Ritorno il risultato quando hunter riceve una risposta dal server');
if ($('#search-results').length == 0) {
$('div.main > section:first-child').before('<section id="search-results"> <ul id="product-results"> <li>Contenuto</li> </ul> </section>');
}
ProductView.render();
}
// search
$('#search-results .close').on('click', function () {
$('#search-results').animate({height:0}, 500, function () {
$(this).remove();
})
});
});
</script>
And this is my external js with backbone
var Search = {
Models: {},
Collections: {},
Views: {},
Templates:{}
}
Search.Models.Product = Backbone.Model.extend({
defaults: search.product.defaults || {},
toUrl:function (url) {
return url.replace(" ", "-").toLowerCase();
},
initialize:function () {
console.log("initialize Search.Models.Product");
this.on("change", function (){
console.log("chiamato evento change del Model Search.Models.Product");
});
this.on("change:text", function () {
console.log("chiamato evento change:text del Model Search.Models.Product");
});
}
});
Search.Collections.Products = Backbone.Collection.extend({
model: Search.Models.Product,
initialize:function () {
console.log("initialize Search.Collections.Products");
console.log(this);
console.log(this.length);
console.log(this.models);
}
});
Search.Views.Product = Backbone.View.extend({
initialize:function () {
console.log("initialize Search.Views.Product");
console.log($(search.product.template).html());
},
template:function (data) {
if (data == null) {
data = this.collection.toJSON();
}
var template = Handlebars.compile($(search.product.template).html());
template(data);
},
render:function () {
console.log($(this.el));
$(this.el.append("TEST"));
//HERE IS THE PROBLEM
// I have tried this.$el.append("TEST");
return this;
}
});
Does this change anything?
var ProductView = new Search.Views.Product({
// new Search.Collections.Products();
collection:ProductList,
el:$("#search-results")[0]
});
I think backbone can accept both jQuery wrapped or not wrapped object and be fine, but I don't know what Backbone version you are using, see if this works
EDIT: From backbone 1.0 sources, it seems backbone can indeed take either a jQuery wrapped object or a regular dom element, it should still work
this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
Do you have something online (JSFiddle?) I will be happy to take a look, but this.$el should work and be equal to $("#search-results") from your code in a quick glance.
Have you tried using ProductView.setElement($("#search-results")) instead? it should be the same, but worth a try as well.