require.config({
baseUrl:'resource',
paths:{
'three': 'lib/threeJS/three.min',
'OrbitControls': 'lib/threeJS/OrbitControls'
},
shim:{
'OrbitControls': {
deps: ['three'],
exports:'OrbitControls'
}
}
});
require(['OrbitControls'],function (OrbitControls) {
});
My test code is shown above and when I debug this code, the console output
THREE is 'OrbitControls.js:16 Uncaught ReferenceError: THREE is not defined(…)'.
However, there is no problem with Three.js(revision=75). So I review the source code of three.js, and I find some differences. The most important one is the different moduling method. Three.js(revision = 80) starts from:
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.THREE = global.THREE || {})));
}(this, (function (exports) { 'use strict';
So anyone could tell me how to add this version of three.js with require.js? In addition, my require.js is ver. 2.1.19
You have to define just path of js on path: i think you have written js name. please change it and then load js using it's name in shim tag.
also refer code from hear
It's correct after appending this code before using it:
define('three', ['../js/lib/threejs/three.82.min'], function ( THREE ) { window.THREE = THREE; return THREE; });
Related
I am new to mocha. My scripts below works when i run from the terminal. However, there is no result when i run from testrunner.html. On checking, it seems to be because of var xl = require('./excel');. if i comment this statement, it works. How can i make this work? i need to import custom modules for my script.
Updated test.js to incorporate RequireJS
Post changes: works on browser and termial
module1.js
if(typeof define !== 'undefined')
{
define([], function() {
return {
get: function() {
return get();
}
};
});
}
else if(typeof exports !== 'undefined') {
module.exports = {
get: function(){
return get();
}
};
}
function get(){
return "hello node world";
}
test.js
if(typeof requirejs == 'undefined') {var requirejs = require('requirejs');}
if(typeof chai == 'undefined') {var chai = require('chai');}
requirejs.config({
baseUrl: '.',
paths: {
},
nodeRequire: require
});
describe("RequireTest()", function(){
var module1;
before(function(done){
requirejs(['./module1'],
function(_module) {
console.log('before fired');
module1 = _module;
if(typeof requirejs == 'undefined') {mocha.run();}
done();
});
});
it('test case: ', function(){
console.log(module1.get());
chai.expect(1+1).to.equal(2);
});
});
testrunner.html (snippet)
<div id="mocha"></div>
<script src="../node_modules/mocha/mocha.js"></script>
<script src="../node_modules/chai/chai.js"></script>
<script src="../node_modules/requirejs/require.js"></script>
<script>mocha.setup('bdd')</script>
<script src="./test.js"></script>
<script>mocha.run();</script>
When you run Mocha at the command line you are using Node.js, which provides require.
When you run it in the browser, there is no require that the browser provides. You need to use a module loader at run-time like RequireJS or SystemJS. Or you need to use a packager like Webpack or Browserify that will process your code beforehand and turn it into a single bundle that incorporates all your code.
Note that whether third-party modules you use can be loaded in a browser, is a determination you have to make module-by-module. If you use a module that uses Node's child_process module to spawn a new process, for instance, you won't be able to just use that module in the browser because browsers don't provide child_process.
I am new to mocha. My scripts below works when i run from the terminal. However, there is no result when i run from testrunner.html. On checking, it seems to be because of var xl = require('./excel');. if i comment this statement, it works. How can i make this work? i need to import custom modules for my script.
Updated test.js to incorporate RequireJS
Post changes: works on browser and termial
module1.js
if(typeof define !== 'undefined')
{
define([], function() {
return {
get: function() {
return get();
}
};
});
}
else if(typeof exports !== 'undefined') {
module.exports = {
get: function(){
return get();
}
};
}
function get(){
return "hello node world";
}
test.js
if(typeof requirejs == 'undefined') {var requirejs = require('requirejs');}
if(typeof chai == 'undefined') {var chai = require('chai');}
requirejs.config({
baseUrl: '.',
paths: {
},
nodeRequire: require
});
describe("RequireTest()", function(){
var module1;
before(function(done){
requirejs(['./module1'],
function(_module) {
console.log('before fired');
module1 = _module;
if(typeof requirejs == 'undefined') {mocha.run();}
done();
});
});
it('test case: ', function(){
console.log(module1.get());
chai.expect(1+1).to.equal(2);
});
});
testrunner.html (snippet)
<div id="mocha"></div>
<script src="../node_modules/mocha/mocha.js"></script>
<script src="../node_modules/chai/chai.js"></script>
<script src="../node_modules/requirejs/require.js"></script>
<script>mocha.setup('bdd')</script>
<script src="./test.js"></script>
<script>mocha.run();</script>
When you run Mocha at the command line you are using Node.js, which provides require.
When you run it in the browser, there is no require that the browser provides. You need to use a module loader at run-time like RequireJS or SystemJS. Or you need to use a packager like Webpack or Browserify that will process your code beforehand and turn it into a single bundle that incorporates all your code.
Note that whether third-party modules you use can be loaded in a browser, is a determination you have to make module-by-module. If you use a module that uses Node's child_process module to spawn a new process, for instance, you won't be able to just use that module in the browser because browsers don't provide child_process.
I'm using react to retrieve data from parse, manipulate it in my own function, and then update a component in the render.
The problem is that I can't update the state within my own, convoluted function unless I attach a string of bind(this). The entire component looks like this:
React.Component({
getInitialState: function () {
return{
isloading:true
}
},
componentDidMount: function(){
this.myStupidFunction()
},
myStupidFunction : function(){
(
(
(nested parse queries that eventually ...
return an object and set isloading:false).bind(this))
.bind(this))
.bind(this)
},
render: function (){
if (this.state.isloading) {
return(
<Text "...isloading"/>
)
} else {
return(
...actually return important stuff...
)
}
}
})
What is the smarter way to do this? Do I need to really .bind(this) for every nested function?
There are a few ways to maintain the context of your component.
Use ES6 Arrows
If you use ES6 arrows to define your functions. Arrow functions force the inner context of this to be the same as the outer context, regardless of how the function is called.
parse.find({
success: results => {
// this is correct
console.log(this);
}
});
I think this is the most elegant solution, but not all browsers support arrow functions yet.
Use Component Methods
React automatically binds this into each of the top level methods on your component. They are always guaranteed to have the correct context.
onSuccess: function() {
// this is correct
console.log(this);
},
componentWillMount: function() {
parse.find({
success: this.onSuccess
});
}
This is also fairly elegant, in my opinion. It lets React deal with the messiness of context whilst you just write code. However, it can mean that you end up with far too many methods at the top level of your component, so use it sparingly.
As an Argument
Some functions, such as map allow you to optionally pass a context to use as this as a final argument. This allows you to maintain the correct context without .bind(this).
data.map(function() {
console.log(this);
// this is correct
}, this);
This only works for some methods, so it's not really a universal solution.
Alias this
Create a reference to this and use that instead.
var __this__ = this;
parse.find({
success: results => {
// __this__ is correct
console.log(__this__);
}
});
This hack has been around forever in Javascript, but I don't think it's a great way to solve the problem.
Use ES7 Function Bind
For those who like to Javascript on the edge, you could also achieve this using the ES7 function bind syntax proposal — currently implemented in Babel.
parse.find({
success: this::function(results) {
// this is correct
console.log(this);
}
});
This requires using experimental proposal stage features of ES7. You may not want to start using it yet, but it's definitely interesting to be aware of. The value on the left hand side will be bound into the function on the right, as this.
Use a closure at the beginning of the function to capture this. It will be usable in any nested structure. The conventional names for such a closure are self _this and that. I prefer self.
myStupidFunction : function(){
var self = this;
someAsyncCall(1,2, function(result) {
//some nested stuff
anotherAsyncCall(1,2 function(innerResult) {
self.setState(innerResult);
});
});
}
one solution could be using local variable
myStupidFunction:function(){
var that=this
ParseReact.Mutation.Create('Place', {
name: 'New Place',
user: Parse.User.current()
})
.dispatch()
.then(function() {
that.refreshQueries();
});
}
Using ES7 Property Initalizer Syntax, currently implemented in Babel.
The key is the methodName = () => { //method return }
You can read more here.
import React from 'react';
export default class Note extends React.Component {
constructor(props) {
super(props);
this.state = {
editing : false
}
}
render() {
const editing = this.state.editing;
return (
<div>{ editing ? this.renderEdit() : this.renderTask() }</div>
)
}
renderEdit = () => {
return (
<input type="text"
className="edit-input"
autoFocus={true}
defaultValue={this.props.task}
onBlur={this.finishEdit}
onKeyPress={this.checkEnter} />
)
}
renderTask = () => {
const onDelete = this.props.onDelete;
return (
<div onClick={this.edit}>
<span className="task-body">{this.props.task}</span>
{ onDelete ? this.renderDelete() : null }
</div>
)
}
renderDelete = () => {
return (
<button className="delete-btn" onClick={this.props.onDelete}>x</button>
)
}
edit = () => {
this.setState({
editing : true
})
}
checkEnter = (e) => {
if(e.key === "Enter") {
this.finishEdit(e);
}
}
finishEdit = (e) => {
this.props.onEdit(e.target.value);
this.setState({
editing : false
})
}
}
// Note: Sample class from project above.
I'm using Rails 3.2.16 and require.js ('requirejs-rails' gem).
My app has a module named ExpensesUI (here is a snippet of it):
$(function() {
define('ExpensesUI', ['OperationsUI'], function(operationsUI) {
var expenses = {
operationConsolidatedCheckbox: "#operation_consolidated",
parcelledNoCheckbox: "#operation_parcelled_no",
parcelledYesCheckbox: "#operation_parcelled_yes",
/* more things */
};
}
});
I can use it perfectly in any .js file with:
require(['ExpensesUI'], function(expensesUI) { console.log(expensesUI.parcelledNoCheckbox); });
But when I try the same require call in a .js.erb, I got 'undefined' logged.
It's not possible to use requirejs with *.js.erb files. Just because requirejs get files out of sprockets.
But instead, you can use named modules in *.html.erb views, for instance:
<script>
define('mymodule', function() {
'use strict';
return {
user: <%= #user.to_json.html_safe %>
};
});
</script>
I am creating an MVC3 application, with requireJS. In my views I need to convert the Model object into a knockout viewmodel object. So I need to use knockout and knockout.mapping libraries.
My application is designed in the following way,
1). All the script files are categorized into folders
Scripts/app/home/ - contains the scripts for the views in Home controller.
Scripts/lib/ - contains the scripts like jQuery, knockout,knockout.mapping, requirejs etc
2). In the "_Layout.cshtml" I am referencing "require.js" like this.
<script src="#Url.Content("~/Scripts/lib/require.js")" type="text/javascript"></script>
3). To configure the require.js settings I am using a different script file called "common.js" (Scripts/lib/common.js)
require.config(
{
baseUrl: "/Scripts/",
paths:{
jquery: "lib/jquery-2.0.3",
ko: "lib/knockout-2.3.0",
komapping: "lib/knockout.mapping"
}
});
4). This is my index.js file which is in 'Scripts/app/home/"
define(['ko', 'komapping'], function (ko, komapping) {
var person = function () {
var self = this;
self.getPersonViewModel = function (data) {
return ko.mapping.fromJS(data); ;
};
};
return { Person: person };
});
5). This is my "Index" action method in the "Home" controller
public ActionResult Index()
{
var person = new Person
{
Id = 1,
Name = "John",
Addresses = new List<Address>(new[]{new Address{Country = "Country 1", City = "City 1"}})
};
return View(person);
}
6). Finally this is my "Index" view
#model MMS.Web.Models.Person
<script type="text/javascript">
require(["/Scripts/common/common.js"], function () {
require(["app/home/index"], function (indexJS) {
var person = new indexJS.Person();
var vm = person.getPersonViewModel(#Html.Raw(Json.Encode(Model)));
});
});
</script>
The problem which I am facing is when loading the index.js file, I get a script error that the knockout.js cannot be loaded.
Failed to load resource: the server responded with a status of 404 (Not Found) - http:///Scripts/knockout.js
But if I remove the dependency of "komapping" inside the "index.js" file it loads correctly, but then I cannot use the mapping functionality.
I had a look inside these links, but couldn't find a solution,
Knockout.js mapping plugin with require.js and
https://github.com/SteveSanderson/knockout.mapping/issues/57
Your help, suggestions are much appreciated. Thanks!
I had the same issue. The problem is that the knockout.mapping defines a knockout dependency, so you need to satisfy this one when you load the script.
Here is how you should load your mapping stuff
require.config(
{
baseUrl: "/Scripts/",
paths:{
jquery: "lib/jquery-2.0.3",
knockout: "lib/knockout-2.3.0",
komapping: "lib/knockout.mapping"
},
shim: {
komapping: {
deps: ['knockout'],
exports: 'komapping'
}
}
});
Then in my case, I use an index.js file with a requirejs call like the following
requirejs(['jquery', 'knockout', 'komapping'], function($, ko, komapping){
ko.mapping = komapping;
//Do other stuff here
});