html element renders as variable name - javascript

While attempting to use React.js and maybe or most likely I am doing something wrong? But when I run React.Render() nothing visible renders, however. Viewing the DOM through Chromes console I can see something happen just nothing anything recognizes.
JSX
/* global React */
var notifying = {};
(function () {
'use strict';
notifying = React.createClass({
getInitialState: function () {
return { isSeen: false };
},
_handleDismissalClick: function () {
this.setState({ isSeen: this.isSeen ? false : true });
},
render: function () {
return ( <div className={'alert alert-success'} role={'alert'}> SOMETHING </div> );
}
});
})();
(function(){
'use strict';
React.render(<notifying />, document.querySelector('.__content'));
})();
JS
/* global React */
var notifying = {};
(function () {
'use strict';
notifying = React.createClass({displayName: "notifying",
getInitialState: function () {
return { isSeen: false };
},
_handleDismissalClick: function () {
this.setState({ isSeen: this.isSeen ? false : true });
},
render: function () {
return ( React.createElement("div", {className: 'alert alert-success', role: 'alert'}, " SOMETHING ") );
}
});
})();
(function(){
'use strict';
React.render(React.createElement("notifying", null), document.querySelector('.__content'));
})();
In the DOM the output is
<notifying data-reactid=".0"></notifying>
can anyone explain to me what I did wrong where so I can stop making this mistake?

You are creating a <notifying /> DOM element. Instead, you need to call the method to create an element, which is then passed to the render method.
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>
<script type="text/jsx">
/* global React */
var notifying = {};
(function () {
'use strict';
notifying = React.createClass({
getInitialState: function () {
return { isSeen: false };
},
_handleDismissalClick: function () {
this.setState({ isSeen: this.isSeen ? false : true });
},
render: function () {
return ( <div className={'alert alert-success'} role={'alert'}> SOMETHING </div> );
}
});
})();
(function(){
'use strict';
React.render(React.createElement(notifying), document.querySelector('.__content'));
})();
</script>
<div class="__content"></div>

Related

ionic modal remove and animation is not working

I am using ionic modal in which once i open the ionic modal and submit the button the ionic remove model is not working as well as even the animation is not working in the modal.I have tried using ionic hide instead of remove but still it is not working can anyone tell me what is the issue in ionic modal.
Modal:
'use strict';
(function () {
angular.module('main')
.service('ModalService', ModalService);
ModalService.$inject = ['$ionicModal', '$log'];
function ModalService ($ionicModal, $log) {
var init = function (tpl, $scope) {
var promise;
var a = $scope;
$scope = a;
promise = $ionicModal.fromTemplateUrl(tpl, {
scope: $scope,
animation: 'slide-in-right'
}).then(function (modal) {
$scope.modal = modal;
return modal;
});
$scope.openModal = function () {
$log.log('openModal function got clicked', $scope);
$scope.modal.show();
};
$scope.closeModal = function () {
$scope.modal.hide();
};
$scope.removeModal = function () {
$scope.modal.remove();
};
$scope.$on('$destroy', function () {
$scope.modal.remove();
});
return promise;
};
return {
init: init
};
}
})();
Controller to call the ionic remove and hide:
function modalFunction (htmlpath) {
vm.modalListType = 'category';
ModalService
.init(htmlpath, $scope)
.then(function (modal) {
$log.log('modal success');
catModal = modal;
catModal.show();
vm.search = '';
});
}
function closeModal () {
catModal.hide();
}
function removeModal () {
$log.log('removeModal got called', catModal);
catModal.remove();
}
Html file :
<div class="center-align">
<button class="button trans-but m-t-10" type="submit" ng-click="vm.addProduct()">{{'save_message' | translate}}</button>
</div>
Function which call the remove function:
function addProduct () {
$log.log('addProduct called: ', vm.product);
var data = [];
data.push({field: vm.product.type, type: 'text', name: $translate.instant('{{"producttype_message" | translate}}')});
data.push({field: vm.product.count, type: 'num', amounttype: 'Advance', name: $translate.instant('{{"ecount_message" | translate}}')});
data.push({field: vm.product.rate, type: 'num', amounttype: 'Advance', name: $translate.instant('{{"eprice_message" | translate}}')});
CommonService.validate(data).then(function () {
//vm.product.total = (vm.product.count - vm.product.deduction) * vm.product.rate;
vm.products.push(vm.product);
closeModal();
removeModal();
}, function (err) {
cordova.plugins.Keyboard.close();
CommonService.toast(err);
});
}
If you try to close the modal with the function, $scope.modal.hide();
Since if you use remove(), you will have to create the modal again.
A possible solution could be:
function closeModal () {
$scope.modal.hide();
}
Or
function closeModal () {
$scope.modal.remove();
}
This would be inside your modalFunction controller.

Jasmine: after using callFake, how can you revert to the original function?

Say that you have spyOn(obj, 'method').and.callFake(fn);. How can you subsequently revert obj.method back to it's original function?
Use case: if you are doing a callFake in a big beforeEach and want to use the original method for one of your test cases, but the fake in the rest.
test.js
var obj = {
method: function () {
return 'original';
},
}
module.exports = obj;
testSpec.js
var obj = require('../test.js');
describe('obj.method', function () {
it('should return "original" by default', function () {
expect(obj.method()).toBe('original');
});
it('should return "fake" when faked', function () {
spyOn(obj, 'method').and.callFake(function () {
return 'fake';
});
expect(obj.method()).toBe('fake');
});
it('should return "original" when reverted after being faked', function () {
spyOn(obj, 'method').and.callFake(function () {
return 'fake';
});
// what code can be written here to get the test to pass?
expect(obj.method()).toBe('original');
});
});
I'm using Jasmine v2.5.2.
Edit: Well, I suppose you could just write:
obj.method = function () {
return 'original';
};
but that feels way too not-DRY. Is there something jasmine-based like obj.method.revertToOriginal()?
You can call callThrough() on spied method to revert it to basic function.
var obj = {
method: function() {
return 'original'
}
}
describe('obj.method', function() {
it('should return "original" by default', function() {
expect(obj.method()).toBe('original');
});
it('should return "fake" when faked', function() {
spyOn(obj, 'method').and.callFake(function() {
return 'fake';
});
expect(obj.method()).toBe('fake');
});
it('should return "original" when reverted after being faked', function() {
spyOn(obj, 'method').and.callFake(function() {
return 'fake';
});
obj.method.and.callThrough() // method for revert spy
expect(obj.method()).toBe('original');
});
});
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>

angular-ui-router function inside controller is not a function

I created a controller inside a state. We usually use this kind of notation for our angular (1.5) components and services with an angular.extend(self, {}).
My problem here is when self.criteria is being initialized, the browser call self.getAgencies() and return an exception :
Error: self.getAgencies is not a function
(function (app) {
'use strict';
app.config(function ($stateProvider) {
$stateProvider.state('app.invoice', {
url: '/invoice'
abstract: true,
template: '<ui-view></ui-view>'
})
.state('app.invoice.list', {
url: '/list?allMyParam',
template: '<invoices criteria="$ctrl.criteria"></invoices>',
controllerAs: '$ctrl',
controller: function ($location) {
var self = this;
angular.extend(self,{
criteria: {
agencies: self.getAgencies()
},
getAgencies: function () {
if ($location.search().agencies) {
return undefined;
} else {
return ['foo', 'blah'];
}
}
});
}
});
});
})(angular.module('module', []));
I put getAgencies() function over the criteria prototype initialization but it did not change anything.
I got out of it by moving getAgencies() outside of angular.extend(self, {}) like this :
var self = this;
var getAgencies = function () {
if ($location.search().agencies) {
return undefined;
} else {
return ['foo', 'blah'];
}
}
angular.extend(self, {
criteria: {
agencies: getAgencies()
}
});
My code is working so it is ok for me but I would like to understand why my self.getAgencies() is not working when this call inside a controller component works well, and make it better if I can.
I'm using angular-ui-router 0.2.18 with angular 1.5.0.
Thank you for your help.
Because when this code is reached
criteria: {
agencies: self.getAgencies()
},
the angular.extend function has not been called yet, and there is no reason why self should contain the getAgencies function.
Why not initialize the agencies afterwards?
angular.extend(self,{
criteria: { },
getAgencies: function () {
if ($location.search().agencies) {
return undefined;
} else {
return ['foo', 'blah'];
}
}
});
self.criteria.agencies = self.getAgencies();
Alternatively, you could use a getter and post-pone calling the function:
angular.extend(self,{
criteria: {
get agencies() {
if (!self._agencies) {
self._agencies = self.getAgencies();
}
return self._agencies;
}
},
getAgencies: ...
});

Polling not working in React JS mixin

So I created the following mixin:
var Polling = {
startPolling: function() {
var self = this;
setTimeout(function() {
self.poll();
if (!self.isMounted()) {
return;
}
self._timer = setInterval(self.poll(), 15000);
}, 1000);
},
poll: function() {
if (!this.isMounted()) {
return;
}
var self = this;
console.log('hello');
$.get(this.props.source, function(result) {
if (self.isMounted()) {
self.setState({
error: false,
error_message: '',
users: result
});
}
}).fail(function(response) {
self.setState({
error: true,
error_message: response.statusText
});
});
}
}
Note the console.log('hello'); in the poll function. I should see this every 15 seconds according to this logic.
Now lets look at a react component:
//= require ../../mixins/common/polling.js
//= require ../../mixins/common/state_handler.js
//= require ../../components/recent_signups/user_list.js
var RecentSignups = React.createClass({
mixins: [Polling, StateHandler],
getInitialState: function() {
return {
users: null,
error_message: '',
error: false
}
},
componentDidMount: function() {
this.startPolling();
},
componentWillUnmount: function() {
if (this._timer) {
clearInterval(this._timer);
this._timer = null;
}
},
shouldComponentUpdate: function(nextProps, nextState) {
if (this.state.users !== nextState.users ||
this.state.error !== nextState.error ||
this.state.error_message !== nextState.error_message) {
return true;
}
return false;
},
renderContents: function() {
if (this.state.users === null) {
return;
}
return (
<div>
<ul>
<UserList users={this.state.users} />
</ul>
</div>
);
},
render: function() {
return (
<div>
{this.loading()}
{this.errorMessage()}
{this.renderContents()}
</div>
)
}
});
RecentSignupsElement = document.getElementById("recent-signups");
if (RecentSignupsElement !== null) {
ReactDOM.render(
<RecentSignups source={ "http://" + location.hostname + "/api/v1/recent-signups/" } />,
RecentSignupsElement
);
}
Here we see in the componetDidMount function I am calling this.startPolling When the page loads, what I see after 1 second is:
hello
hello
A) its (poll fucntion) some how being called twice oO.
B) its (poll function) never being called again.
The reason I separated polling out is so that I can use it in other components on the same page and not duplicate code.
Very simply question(s):
Why and how do I fix this? I need it to poll ever 15 seconds and I should only see hello once when poll is called the first time.
On this line you call self.poll() and the result would be the timer:
self._timer = setInterval(self.poll(), 15000);
Instead pass the function:
self._timer = setInterval(self.poll, 15000);
As another option, in the spirit of "you're code's not working? just use someone else's instead!", react-async-poll is a handy component wrapper that you can use for polling.

Testing RequireJS modules with QUnit

I'm trying to test a requirejs module that has two dependencies (jquery and another custom module).
myModule-Test.js
'use strict';
(function() {
var uut,
modulePath= "../../main/webapp/js/modules/myModule.js";
module("myModule object test suite", {
setup: function() {
QUnit.stop();
require.config({
map: {
"*": {
"jquery": "../../main/webapp/js/jquery/jquery-1.11.0.min.js",
"screenLabelsResolver": "../../main/webapp/js/modules/my-screen-labels-resolver"
}
}
});
require([modulePath], function(module) {
uut = module;
QUnit.start();
});
},
teardown: function() {
require.undef(modulePath);
require.config({
map: {
"*": {
"jquery": "jquery",
"screenLabelsResolver": "../../main/webapp/js/modules/my-screen-labels-resolver"
}
}
});
}
});
test("Given A Page I Expect The Global myModule Object To Exist", function() {
ok( uut !== undefined );
});
}());
I am using require.config to pass in the dependencies with stop() and a Start().
myModule.js
'use strict';
define(["jquery", "screenLabelsResolver"], function($, screenLabelsResolver) {
var metaTag = $("meta[name='application-name']"),
currentBrand = metaTag.attr("data-brand"),
currentWidth,
viewState,
sessionTimeoutValue = metaTag.attr("data-sessiontimeoutvalue"),
sessionTimeoutWarningValue = metaTag.attr("data-sessiontimeoutwarningvalue"),
screenLabels = {},
perceptionDate = metaTag.attr("data-todayatmidnight"),
currentViewportWidth = $(window).width(),
isViewState = metaTag.attr("data-isviewstate"),
isTouch = $("html").hasClass("touch")
return {
metaTag: function () {
return metaTag;
},
currentBrand: function(){
return currentBrand;
},
currentViewportWidth: function(){
return currentViewportWidth;
},
isViewState: function(){
return isViewState;
},
sessionTimeoutValue: function(){
return sessionTimeoutValue;
},
sessionTimeoutWarningValue: function(){
return sessionTimeoutWarningValue;
},
getPerceptionDate: function(){
return perceptionDate;
},
getOrientation: function () {
return ( window.orientation == -90 || window.orientation == 90 ) ? "landscape" : "portrait";
},
isTouch: function(){
return isTouch;
},
screenLabels: function() {
if (screenLabels = {}) {
screenLabels = screenLabelsResolver( metaTag.attr("data-viewstate") /* or however you want to get the current viewstate name */ );
}
return screenLabels;
}
};
});
I get the error "Uncaught TypeError: undefined is not a function" where I try to use jQuery ($) in line var metaTag = $("meta[name='application-name']").
Somehow, jQuery is not loaded properly by the time the call is made.
My question that is this the correct approach to test r.js modules with multiple dependencies? If so what's the fundamental error in the above code?
Many Thanks in advance.

Categories