How do You Deal with Reference Errors in Flutter Web? - javascript

The Problem and What I've Done So Far
Abstract: I'm getting a reference error, probably from a package I've imported, that I'd like to know if I can fix on my own. I'm building/testing with flutter-web
I'm writing a flutter app that processes some markdown/LaTeX using the flutter_tex package. Unfortunately when I add a TeXView() widget to my app and try to reload I get:
ReferenceError: OnPageLoaded is not defined
at http://localhost:40111/assets/packages/flutter_tex/js/katex/index.html:50:5
new-447 old-750
It seems to me that there isn't anything in my code that could have caused this error and that it is something wrong with the way that my code gets compiled for the web. I have added this line:
<script src="assets/packages/flutter_tex/js/flutter_tex.js"></script>
to my project's index.html as advised in the installation instructions.
The developer of this package has not responded to issues on GitHub for nearly half a year and someone else has come across this problem before but, I need the features that this package offers so it really isn't an option for me to try a different package.
What I want to know is if there is a general way that I can deal with this. I am new to dart and I'm not even sure where to find most of these files or if any changes that I make will persist after reloading. I do know from the question How do you use onPageLoad in Javascript? that onPageLoad may be replaceable with window.onload but I'm not sure if this is related to my issue.
The Code
import 'package:flutter_tex/flutter_tex.dart';
// <!--Snip--!>
class CardView extends StatefulWidget {
final String deck;
final TeXViewRenderingEngine renderingEngine;
CardView(
{this.deck, this.renderingEngine = const TeXViewRenderingEngine.katex()});
#override
State<CardView> createState() => _CardViewState(deck: deck);
}
class _CardViewState extends State<CardView> {
final String deck;
var _card = jsonDecode('{}');
var _cardId = 0;
var _testString = r"""
*This should be bold*
# This should be a title.
$x=3$
\(x=3\)
$$x=3$$
Hello $x=3$ \(x=3\)""";
_CardViewState({this.deck});
// <!--Snip--!>
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Decks > Deck')),
body: Center(
// child: RichText(
// text: TextSpan(
// text: _card.toString(),
// style: TextStyle(color: Colors.black, fontSize: 18)))
child: TeXView(child: TeXViewMarkdown(_testString.toString()))));
}
}

Related

Why is a function provided by require undefined in a class instance? [duplicate]

This question already has an answer here:
Require returns an empty object
(1 answer)
Closed 1 year ago.
I'm asking this mostly as a sanity check, I'm unsure if I have made a mistake somewhere or if this fundamentally does not work.
I am converting some Java to Nodejs, A class called Site populates itself from a database via the dataFunctions.getSiteInfo(id) function. It also stores a list of Page instances.
The issue is that dataFunctions is returning as undefined when an instance of Site is created.
Have I misunderstood how classes and modules work in this case? Is it possible for instances of this class to access the dataFunctions module? Likewise is it possible for the Site class to reference the Page class as well? Or have I made some other silly mistake?
Site.js
let Page = require('./Page.js');
let dataFunctions = require('../DataFunctions.js');
module.exports = class Site {
constructor(id) {
this.id = id;
this.pages = [];
console.log(dataFunctions);
this.siteInfo = dataFunctions.getSiteInfo(id);
DataFunctions.js
let Site = require('./classes/Site.js');
function makeASite() {
let id = 2;
let site = new Site(id);
}
function getSiteInfo(id) {
etc etc
}
module.exports = {
getSiteInfo: function (id) {
return getSiteInfo(id);
},
};
Based on the code provided, I believe you forgot to create a new dataFunctions instance.
const df = new dataFunctions();
console.log(df);
If dataFunctions is providing static functions, make sure that the getSiteInfo method is static.
Otherwise, additional details may be needed.
Edit
It looked like the project structure and the require paths were wonky, but it's hard to tell.
When I run the code provided using the project structure inferred by the require statements, I'm not able to reproduce your issue.
However, one problem that I do see is that you're requiring the Site.js module from the DataFunctions.js module and requiring the DataFunctions.js module from the Site.js module, creating circular dependencies. Try eliminating these by moving makeASite to the Site.js module, for instance.

Trying to add phaser-swipe file to my typescript project

I'm pretty new to javascript and typescript and I'm having difficulty adding a library to my project.
I have a phaser.io typescript project in VS2017 and I'm trying to add this library to it:
https://github.com/flogvit/phaser-swipe
I've copied the definitions file into my folder "tsDefinitions\phaser-swipe.d.ts" and copied the js file into "build\libs\swipe.js"
I added a reference to the definition file in my project.
/// <reference path="phaser-swipe.d.ts" />
When I try to create the swipe class like in the documents I get the error "Cannot find name Swipe".
My Level01.ts:
export class Level01 extends Phaser.State {
background: Phaser.Sprite;
music: Phaser.Sound;
player: Player;
swipe: Swipe;
create() {
this.background = this.add.sprite(0, 0, 'level01-sprites','background');
this.player = new Player(this.game, this.world.centerX, this.world.centerX);
this.player.anchor.setTo(0, 5);
//Here is where the intellisense error is occurring
this.swipe = new Swipe(this.game);
}
}
Quick Actions adds the following to the top of the file, but it then breaks Phaser.Player and other references by giving the same "Cannot find name Player" error.
import Swipe from "phaser-swipe";
swipe.js:
https://github.com/flogvit/phaser-swipe/blob/master/swipe.js
phaser-swipe.d.ts: https://github.com/flogvit/phaser-swipe/blob/master/phaser-swipe.d.ts
Am I missing something here? How can I get the definitions file to work correctly? Thanks!
Just a wild guess that you should try making it a variable like
var Swipe = require(‘phaser-swipe’);
//Then in your create
this.swipe = new Swipe(this.game);
//then in the update it’ll be all just depending how you want to use it.
Always check your comas”,” and this”;” cz a simple coma can give you errors trust me I know x) hope it helps.

Working with KendoUI, TypeScript and DefinitelyTyped

I'm working with an old version of KendoUI (v2013.2.716) and TypeScript (v 0.9.5). I would update, but everything breaks and I'm on a tight deadline. Will do that later.
Anyway, I'm using the DefinitelyTyped kendo.d.ts and everything was fine until I tried this:
var grid = $('.k-grid').data('kendoGrid');
grid.dataSource.transport.options.read.url = newDataSource;
grid.dataSource.read();
This works fine, but Visual Studio doesn't like it. I get:
The property 'transport' does not exist on value of type 'kendo.data.DataSource'
I've had issues like this before and pretty sure I can make a custom.d.ts file to work around this error, but not sure how. Does anyone know how I can create a workaround?
You can 'extend' existing type interfaces by simply declaring them twice, they will be merged.
So, this:
interface A {
propB: string;
}
interface A {
propC: number;
}
Will be treated by the compiler as:
interface A {
propB: string;
propC: number;
}
In your case you can add a custom declaration file, and add the following:
module kendo {
interface data {
interface DataSource {
transport: any;
}
}
}
Of course, you can add typings for transport as well.
I have run into similar issues.
Most of the times, I fixed it by casting it to any.
Try this -
(<any>grid.dataSource.transport).options.read.url = newDataSource;
Or, you can try this too -
(<kendo.data.DataSource>.grid.dataSource).transport.options.read.url = newDataSource;
But, fist option should work for sure!
Hope, this helps
This is not a particularly elegant answer, but here's what I do on a tight deadline:
grid.dataSource['transport'].options.read.url = newDataSource;
To me this is generally not advised as the whole reason you're using typescript is to maintain type safety, however in the case of 3rd party libraries I do make exceptions here and there by casting to any or using indexer syntax as above.

Can't create javascript XPCOM service for Firefox extension

I've been banging my head a against this particular brick wall now for more than two days. I am attempting to create an XPCOM service for use in a Firefox extension but am unable to initialise the component with the following error displayed in the error console in Firefox.
Timestamp: 07/06/2012 09:23:28 Error: uncaught exception: [Exception...
"Component returned failure code: 0x80570016 (NS_ERROR_XPC_GS_RETURNED_FAILURE)
[nsIJSCID.getService]" nsresult: "0x80570016 (NS_ERROR_XPC_GS_RETURNED_FAILURE)"
location: "JS frame :: chrome://logger/content/logger.js :: <TOP_LEVEL> :: line 21"
data: no]
I have reduced the component to the bare minimum using the excellent boilerplate generator at ted.mielczarek.org. The component code is as follows...
const nsISupports = Components.interfaces.nsISupports;
const CLASS_ID = Components.ID("808e1607-caea-418c-b563-d9fe1df6ee08");
const CLASS_NAME = "Test component";
const CONTRACT_ID = "#test/loggerservice;1";
function LoggerService() {
this.wrappedJSObject = this;
}
LoggerService.prototype = {
QueryInterface: function(aIID)
{
if (!aIID.equals(nsISupports))
throw Components.results.NS_ERROR_NO_INTERFACE;
return this;
}
}
The remainder of the boilerplate that creates the module and factory interfaces is unchanged.
The chrome.manifest file looks like this...
content logger chrome/content/
skin logger classic/1.0 chrome/skin/
locale logger en-US chrome/locale/en-US/
component {808e1607-caea-418c-b563-d9fe1df6ee08} components/loggerservice.js
contract #test/loggerservice;1 {808e1607-caea-418c-b563-d9fe1df6ee08}
overlay chrome://browser/content/browser.xul chrome://logger/content/logger-overlay.xul
style chrome://global/content/customizeToolbar.xul chrome://logger/skin/overlay.css
Finally, the logger-overlay.xul file includes a script file - logger.js - which attempts to get a reference to the LoggerService component using the following code...
this.loggerService = Components.classes["#test/logger;1"].getService().wrappedJSObject;
and it is this line that is reporting in the firefox error console.
I can't see how much simpler I can make it - any insight would be very much appreciated.
This is a nice boilerplate generator but unfortunately an outdated one. For one, you should be using XPCOMUtils, this will get rid of most of the boilerplate. More importantly, this boilerplace generator hasn't been updated to XPCOM changes in Gecko 2.0 and defines NSGetModule function instead of NSGetFactory. Module code like this should work however:
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
function LoggerService() {
this.wrappedJSObject = this;
}
LoggerService.prototype = {
classID: Components.ID("808e1607-caea-418c-b563-d9fe1df6ee08"),
classDescription: "Test component",
contractID: "#test/loggerservice;1",
QueryInterface: XPCOMUtils.generateQI([])
}
if ("generateNSGetFactory" in XPCOMUtils)
var NSGetFactory = XPCOMUtils.generateNSGetFactory([LoggerService]); // 2.0+
else
var NSGetModule = XPCOMUtils.generateNSGetModule([LoggerService]); // 1.9.x
You can remove the NSGetModule code if your extension doesn't need to be compatible with Firefox 3.6. You can also remove the classDescription and contractID properties then, these are specified in chrome.manifest already.
Note: If you only need an object that will stay around for the entire browsing session and can be accessed from anywhere then a JavaScript code module would be a better choice - no XPCOM boilerplate and no wrappedJSObject hacks.

Using code in both Actionscript3 and Javascript

Here's an interesting architectural query. I have a piece of code that needs to run on the server (under Node.js) and on the client (in a Flash 10 app written with Actionscript 3). The code is mostly fairly intricate object manipulation, it doesn't make any API calls, and works fine in both contexts.
So far the project is just a demo, so I've been happy to copy and paste the code into both places. But it might be quite interesting to move forward with this.
So how would you do it?
I assume there is no easy way to get the Flash SDK (has to build without an IDE) to read and do something useful with a .js file.
My only thought is that I could write a code-generator that takes the .js file and places it in an ActionScript wrapper.
Are there any obvious approaches that I've missed?
Just to pre-empt an obvious answer, I know about cross-platform languages like Haxe.
A possible way is using include in your wrapper Actionscript code. Just a quick and very simple test:
package {
import flash.display.Sprite;
import flash.text.TextField;
public class Main extends Sprite {
private var _alertTxt:TextField;
include "some.js"
public function Main() {
_alertTxt = new TextField();
_alertTxt.multiline = true;
_alertTxt.height = 400;
_alertTxt.width = 400;
addChild(_alertTxt);
run();
}
public function alert(msg) {
_alertTxt.text += msg + "\n";
}
}
}
some.js
function run() {
alert("run");
var obj = {
a : 'hello',
b : 4.5,
c : false
};
loop(obj);
}
function loop(obj) {
for (var field in obj) {
alert(obj[field]);
}
}
To compile from command-line (you might want to add other options):
mxmlc -strict=false Main.as
If you don't set strict to false, it won't compile because of the lack of type declarations.

Categories