Pass a config-node parameter within HTML-File to another node - html

I created following input-node:
<script type="text/javascript">
RED.nodes.registerType('Sensor',{
category: 'input',
defaults: {
name: {type:"InputDevice", required:true},
count: {value:"", required:true, validate:RED.validators.number()},
topic: {value:"",validate: RED.validators.regex(/^(#$|(\+|[^+#]*)(\/(\+|[^+#]*))*(\/(\+|#|[^+#]*))?$)/)},
qos: {value: "1"},
broker: {type:"mqtt-broker", required:true},
},
color:"#3FADB5",
inputs:0,
outputs:1,
icon: "feed.png",
label: function() {
//var testu = RED.nodes.getNode(config.name).inputDeviceName;
//return this.name.inputDeviceName;
return this.name||this.topic||"ClientName";
},
labelStyle: function() {
return this.name?"node_label_italic":"";
},
});
And following config node:
<script type="text/javascript">
RED.nodes.registerType('InputDevice',{
category: 'config',
defaults: {
inputDeviceName: {value:"",required:true},
},
label: function() {
return this.inputDeviceName;
}
});
I can not figure out, how to pass over the parameter
inputDeviceName
to my Sensor node within the HTML File. Within the JS File, i am able to get the value of inputDeviceName with:
this.name = RED.nodes.getNode(config.name).inputDeviceName;
How can I name the sensor-node, like in the example above, to appear as 'LDR' in my flow?

You can access the properties of any node for which you know the id in a HTML file with RED.nodes.node(node_id). This will return this nodes default properties.
If you, for example, need some property from a config node, you can get its id from the value of the select HTML-element associated with the config node.

Related

How to get console output using Polymer?

I have this part of code inside dom-module tag:
<script>
Polymer({
is: "hi-world",
properties:{
name: {
type: String,
value: "default";
},
edad: {
type: Number;
},
created: function(){
console.log("The element was created")
console.log(this)
console.log(this.$)
console.log(this.$.title);
}
}
})
</script>
But when I execute the code, nothing happens in console at Chrome, Firefox or even (sorry about this) IE. What am I doing wrong? I see some guide lines at https://www.polymer-project.org/1.0/docs/devguide/registering-elements, but it doesn't work.
Also, I tried with one line console.log, with:
created: function(){
console.log("The element was created");
}
And, again, no results in web browser console.
EDIT 1:
According to a1626, the code would be, actually the solution:
<script>
Polymer({
is: "hi-world",
properties:{
name: {
type: String,
value: "default";
},
edad: {
type: Number;
}
},
created: function(){
console.log("The element was created")
console.log(this)
console.log(this.$)
//console.log(this.$.title) <-- commented, it collapses with created method
}
})
</script>
You have placed created callback inside the properties object. And during created callback elements are not prepared so you won't find using this.$.id

EXTJS How to use JSon Reader without proxy

Below is the code where I try to load some records using JSon Reader in the store.
I am unable to see this on the Grid.
Can you please point me out what am I missing as I don't want to use proxy/url for JSon.
var itemsPerPage = 10;
Ext.Loader.setConfig({enabled: true});
Ext.require([
'Ext.grid.*',
'Ext.data.*',
'Ext.util.*',
'Ext.toolbar.Paging'
]);
Ext.define('Assemble', {
extend: 'Ext.data.Model',
fields: [
{name: 'lot_no', type: "string"}
],
idProperty: 'lot_no'
});
Ext.onReady(function() {
Ext.QuickTips.init();
var jsonString = '{"result":[{"lot_no":"MT6261"},{"lot_no":"MT6262"},{"lot_no":"MT6263"}]}';
// create the data store
var store = Ext.create('Ext.data.Store', {
pageSize: itemsPerPage,
proxy:{
type: 'ajax',
reader: {
type: 'json',
root: 'result',
model: Assemble
}
}
});
store.loadData(Ext.decode(jsonString));
console.log(store);
var pagingToolbar = Ext.create('Ext.PagingToolbar',{
pageSize: itemsPerPage,
store: store,
displayInfo: true,
displayMsg: ' {0}-{1},{2}',
emptyMsg: "empty."
});
// create the Grid
var grid = Ext.create('Ext.grid.Panel', {
store: store,
disableSelection: true,
loadMask: true,
columns: [
{
text : 'LOT_NO',
flex : 1,
sortable : true,
dataIndex: 'lot_no'
}
],
bbar : pagingToolbar,
renderTo: 'grid',
viewConfig: {
stripeRows: true,
enableTextSelection: true
}
});
store.loadPage(1);
});
Proxy has to use with url. So, you can't use the proxy like that. I removed the proxy, put the model in store and you have to load objects into store, but in your case contained rootProperty('result', I only get the main objects or you can remove the 'result' from the jsonString). Then, it worked. Chck this fiddle:
https://fiddle.sencha.com/#fiddle/11or
var jsonString = '{"result":[{"lot_no":"MT6261"},{"lot_no":"MT6262"},{"lot_no":"MT6263"}]}';
// create the data store
var store = Ext.create('Ext.data.Store', {
pageSize: itemsPerPage,
model: 'Assemble'
});
store.loadData(Ext.decode(jsonString).result);
Why are you even using a reader? Your data is local so just decode the string and pass in what you want:
https://fiddle.sencha.com/#fiddle/11qc
Also, your data is local so no need for a paging toolbar. In Ext JS 5+ the grid will use the buffered renderer (if the grid has a defined size from height/width configs or from a parent layout) so loading all the data into the store will not affect performance (other than creating the records). The grid will only render what is viewable plus a few on either side.

Extjs 3.4 populate grid after ajax call

Using Extjs 3.4
My web service respond with a json string: {"msg":"Some"}
I want to populate a grid with Some .
Ext.onReady(function(){
var store = new Ext.data.JsonStore({
url: "my/json/url.json",
fields: [{name:"msg"}]
});
function StoreLoadCallback(records, operation, success){
if (success) {
console.log(records); // record is undefined
alert(records); // show 'undefined'
} else {
console.log('error');
}
}
function ajaxSearch_function(){
var query = Ext.getCmp('search').getValue();
store.load({
params: {query: query},
callback: StoreLoadCallback
});
}
var form = new Ext.FormPanel({
defaultType: 'textfield',
items: [{
fieldLabel: 'search',
name: 'search',
id: 'search'
}],
buttons: [{
text: 'Search', handler: ajaxSearch_function
}]
});
form.render('ajax-search_form');
var grid = new Ext.grid.GridPanel({
store: store,
columns: [{
id :'title',
header : 'title',
sortable : true,
dataIndex: 'title'
}],
});
grid.render('ajax-grid');
});
The web service respond well, I have tested with Curl.
The problem is populate the grid with the json response.
If you say that records variable in callback method is undefined, there is probably a problem with parsing the response. I guess it expects array instead of one single record. Try to change the contents of the json file from {"msg" : "Some"} to [{"msg" : "Some"}]
After you cross this hurdle (i. e. the response is correctly parsed), I see that your datagrid column refer to "title" rather than "msg". Title is not a member of the store, so the columns will show empty value anyway.
Also, it is not common to start method name with capital letters (except they represent "classes"), so it is kind of nicer to call the method storeLoadCallback instead of StoreLoadCallback.

Observe changes for an object in Polymer JS

I have an element with a model object that I want to observe like so:
<polymer-element name="note-editor" attributes="noteTitle noteText noteSlug">
<template>
<input type="text" value="{{ model.title }}">
<textarea value="{{ model.text }}"></textarea>
<note-ajax-button url="/api/notes/" method="POST" model="{{model}}">Create</note-ajax-button>
</template>
<script>
Polymer('note-editor', {
attached: function() {
this.model = {
title: this.noteTitle,
text: this.noteText,
slug: this.noteSlug
}
},
});
</script>
</polymer-element>
I want to observe changes in the model but apparently it's not possible to use modelChanged callback in the element and neither in the note-ajax-button element. What is wrong? How can I do that?
I've tried observing the fields separately, but it's not clean at all. The state of the button element you see there should change depending on the model state, so I need to watch changes for the object, not the properties.
Thanks!
To observe paths in an object, you need to use an observe block:
Polymer('x-element', {
observe: {
'model.title': 'modelUpdated',
'model.text': 'modelUpdated',
'model.slug': 'modelUpdated'
},
ready: function() {
this.model = {
title: this.noteTitle,
text: this.noteText,
slug: this.noteSlug
};
},
modelUpdated: function(oldValue, newValue) {
var value = Path.get('model.title').getValueFrom(this);
// newValue == value == this.model.title
}
});
http://www.polymer-project.org/docs/polymer/polymer.html#observeblock
Or you can add an extra attribute to your model called for example 'refresh' (boolean) and each time you modify some of the internal values also modify it simply by setting refresh = !refresh, then you can observe just one attribute instead of many. This is a good case when your model include multiple nested attributes.
Polymer('x-element', {
observe: {
'model.refresh': 'modelUpdated'
},
ready: function() {
this.model = {
title: this.noteTitle,
text: this.noteText,
slug: this.noteSlug,
refresh: false
};
},
modelUpdated: function(oldValue, newValue) {
var value = Path.get('model.title').getValueFrom(this);
},
buttonClicked: function(e) {
this.model.title = 'Title';
this.model.text = 'Text';
this.model.slug = 'Slug';
this.model.refresh = !this.model.refresh;
}
});
what I do in this situation is use the * char to observe any property change in my array, here an example of my JSON object:
{
"config": {
"myProperty":"configuraiont1",
"options": [{"image": "" }, { "image": ""}]
}
};
I create a method _myFunctionChanged and I pass as parameter config.options.* then every property inside the array options is observed inside the function _myFunctionChanged
Polymer({
observers: ['_myFunctionChanged(config.options.*)']
});
You can use the same pattern with a object, instead to use an array like config.options. you can just observe config.

Extjs - How to refer the json datas in a controller?

I'm developing a simple login page wherein I need to compare the value that has been entered by any user in username field, with the json data store on click of 'LoginButton'. My question is, can we get the list of username from the json store in an array and compare with textfield values? If so, how?
My nSpaceIndex.html
<html>
<head>
<title>nSpace | Expense / Project Solutions</title>
<link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css">
<script type="text/javascript" src="extjs/ext-debug.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
</body>
</html>
app.js:
Ext.application({
requires: ['Ext.container.Viewport'],
name: 'nSpace',
controllers: [
'nSpaceController'
],
appFolder: 'app',
launch: function() {
Ext.create('Ext.container.Viewport', {
layout: 'fit',
items: {
xtype: 'loginView'
}
});
}
});
my nSpaceController.js:
Ext.define('nSpace.controller.nSpaceController', {
extend: 'Ext.app.Controller',
stores: [
'Users'
],
views: [
'login.loginView'
],
model: 'loginModel',
init: function() {
this.control({
"#loginButton": {
click: this.onLoginButtonClick
}
});
},
onLoginButtonClick: function(){
//var jsonArray = store.Users.data.items
//console.log(jsonArray);
// I NEED TO GET THE REFERENCE OF MY STORE: USERS TO COMPARE
var logUserName = Ext.getCmp('getUserName').getValue();
var logPassword = Ext.getCmp('getPassword').getValue();
if(logUserName == 'user01' && logPassword == 'password01'){
Ext.MessageBox.show({title: 'Success', msg: 'You will be redirected to the home page in few moments...', icon:Ext.MessageBox.INFO});
}
else if(logUserName == 'user02' && logPassword == 'password02'){
Ext.MessageBox.show({title: 'Success', msg: 'You will be redirected to the home page in few moments...', icon:Ext.MessageBox.INFO});
}
else{
Ext.MessageBox.show({title: 'OOPS!!!', msg: 'Please Enter Valid Details', icon:Ext.MessageBox.WARNING});
}
},
});
my loginModel.js:
Ext.define('nSpace.model.loginModel', {
extend: 'Ext.data.Model',
fields: ['loginusername', 'password']
});
Users.js:
Ext.define('nSpace.store.Users', {
extend: 'Ext.data.Store',
model: 'nSpace.model.loginModel',
autoLoad : true,
proxy: {
type: 'ajax',
url: 'data/users.json',
reader: {
type: 'json',
root: 'users',
successProperty: 'success'
}
}
});
loginView.js:
Ext.define('nSpace.view.login.loginView' ,{
extend: 'Ext.form.Panel',
alias: 'widget.loginView',
store: 'Users',
title: 'nSpace | Login',
frame:true,
bodyPadding: 5,
width: 350,
layout: 'anchor',
defaults: {
anchor: '100%'
},
defaultType: 'textfield',
items: [{
fieldLabel: 'User Name',
name: 'loginusername',
id: 'getUserName',
allowBlank: false
},{
fieldLabel: 'Password',
inputType: 'password',
id: 'getPassword',
name: 'password',
allowBlank: false
}],
// Reset and Submit buttons
buttons: [{
text: 'Sign Up',
handler: function() {
// location.href = 'signUp.html';
}
},{
text: 'Reset',
handler: function() {
this.up('form').getForm().reset();
}
}, {
text: 'Login',
id:'loginButton',
formBind: true, //only enabled once the form is valid
disabled: true,
}],
renderTo: Ext.getBody()
});
users.json:
{
"success": true,
"users": [
{"loginusername": 'user01', "password": 'password01'},
{"loginusername": 'user02', "password": 'password02'}
]
}
inside init function above this.control
try using this..
var store = this.getUsersStore();
store.load({
callback:function(){
var l = store.first();
console.log(l.get("password"));
}
});
this is how you can check
store.each(function(rec){
if (rec.get('password') === value) {
display = rec.get('username');
return false;
}
});
As other users have pointed out, it is trivial to perform authorization on the client side of the application. However you have stated that this is not a concern, therefore I will answer your question without addressing the obvious security flaws of this approach.
I see that you're making use of Ext.getCmp() therefore your components have been assigned an id. This is generally considered to be bad practice as the id property is global, and therefore if there are two components instantiated with the same id, the application will crash. You may find it useful to instead assign the component an itemId and create a reference to easily retrieve the component in the Controller's refs[] definition.
For example:
Ext.define('nSpace.controller.nSpaceController', {
... other store/model/view here ...
refs: [{
name: 'userNameField', // makes magic method 'getUserNameField()'
selector: 'textfield[name=loginusername]',
xtype: 'textfield'
},{
name: 'passwordField', // makes magic method 'getPasswordField()'
selector: 'textfield[name=password]',
xtype: 'textfield'
}],
this.control({ .. observe events here .. });
});
Retrieve a reference to your store, and search for the provided user...
var me = this, // controller
store = Ext.getStore('Users'),
user = me.getUserNameField.getValue(),
pass = me.getPasswordField().getValue(),
success;
// Attempt to find a record matching the provided user/pass
success = store.findBy(function(rec){
return (rec.get('loginusername') === user && rec.get('password') === pass);
});
// Store findBy returns the index, or -1 if no matching record is found
if(success >= 0){
// user/password matched
}else{
// no user/password match found
}