Could I use method call from mounted function? - javascript

Could I use method call from mounted function?
in my code, I used this method.
mounted() {
this.initEvent();
this.getnewD(
$(function () {
$("#file-manager").dxFileManager({
name: "fileManager",
fileSystemProvider: customProvider,
currentPath: "Documents",
rootFolderName: "Root",
height: 450,
onErrorOcurred: function (e) {
debugger;
console.log(e);
},
permissions: {
create: true,
copy: true,
move: true,
delete: true,
rename: true,
},
customizeDetailColumns: (columns) => {
columns.push({
caption: "Creator",
dataField: "dataItem.creator",
});
return columns;
},
});
}));
},
And in my methods, I tried to used this methods to call mounted function.
But I got the customProvider is not a function.
So where has problem in my code?
methods: {
arr.forEach((item) => {
let tokens = item.path.replace(/^\/|\/$/g, "").split("/");
let current = tree;
for (let i = 0; i < tokens.length; i++) {
if (!current[tokens[i]]) {
current[tokens[i]] = {};
}
current = current[tokens[i]];
}
});
const parseNode = function (node) {
return Object.keys(node).map((key) => {
if (Object.keys(node[key]).length === 0) {
return {
isDirectory: false,
name: key,
};
}
return {
isDirectory: true,
name: key,
items: parseNode(node[key]),
};
});
};
let result = parseNode(tree);
var objectProvider =
new DevExpress.fileManagement.ObjectFileSystemProvider({
data: new_r,
});
var customProvider =
new DevExpress.fileManagement.CustomFileSystemProvider({
getItems: function (pathInfo) {
return objectProvider.getItems(pathInfo);
},
renameItem: function (item, name) {
if (item.name == "Parent1") {
console.log("error in custom provider");
throw {
errorId: 0,
fileItem: item,
};
console.log("error in custom provider");
} else return objectProvider.renameItem(item, name);
},
createDirectory: function (parentDir, name) {
if (parentDir.name == "Parent1") {
throw {
errorId: 0,
fileItem: item,
};
} else return objectProvider.createDirectory(parentDir, name);
},
deleteItem: function (item) {
console.log(item);
if (item.name == "Parent1") {
throw {
errorId: 0,
fileItem: item,
};
} else return objectProvider.deleteItems([item]);
},
moveItem: function (item, destinationDir) {
if (item.name == "Parent1") {
throw {
errorId: 0,
fileItem: item,
};
} else
return objectProvider.moveItems([item], destinationDir);
},
copyItem: function (item, destinationDir) {
if (item.name == "Parent1") {
throw {
errorId: 0,
fileItem: item,
};
} else
return objectProvider.copyItems([item], destinationDir);
},
});
let new_r = (self.fileSystemProvider = [
{
name: "Security Manager",
isDirectory: true,
items: result,
},
]);
}
I could got the data, but couldn't got some function and displayed the customProvider is not a function.

This has no proper function name in methods: { }
arr.forEach((item) => { ... }
Your methods need to be named!
You need something like that in your methods: object:
methods: {
myfunction(items) {
items.forEach((item) => {
...
}
}
Now you can call myfunction(arr) somewhere else in your script tags
mounted() works with plain js code inside because it is a named lifecycle hook. The methods: { } object however is not a function.

Related

How can I fix my code to work my dispatch with Redux

I use Redux, and I have some problem with dispatch. It doesn't work like it should work. When i dispatched some information, finally I have in state an empty array, but it should be array with object.
It's my code:
if(printDrawingsRedux.imagesCounter.length === 0) {
//Создаём массив для идентификации кол-ва резервируемых блоков под фото
const arrNew = fd.map((value, index) => {
let result
return result = {...value, id: index, link: false, quantity: 1,
type: value.type,
name: value.name,
blackWhitewRateCost: 50,
colorRateCost: 100,
drawingPages: [],
currentNumberPage: 1,
howManyPages: function () {
return this.drawingPages.length
},
modalPlusSize: false,
}
})
dispatch(setImageCounterDrawingsRedux(arrNew))
console.log(printDrawingsRedux.imagesCounter)
}else{
const arrNew = fd.map((value, index) => {
let result
return result = {...value, id: index, link: false, quantity: 1,
type: value.type,
name: value.name,
blackWhitewRateCost: 50,
colorRateCost: 100,
drawingPages: [],
currentNumberPage: 1,
howManyPages: function () {
return this.drawingPages.length
},
modalPlusSize: false,
}
})
let newState = [...printDrawingsRedux.imagesCounter, ...arrNew]
let arrNew2 = newState.map((value, index) => {
return {...value} = {...value, id: index}
})
dispatch(setImageCounterDrawingsRedux(arrNew2))
}
//Делаем итерацию по созданному массиву для наполнения контентом
const promiseArrayBuffer = (file) => new Promise((resolve) => {
var fileReader = new FileReader();
fileReader.onloadend = (e) => resolve(e.target.result);
fileReader.readAsArrayBuffer(file);
});
(async function () {
for (let i = 0; i < fd.length; i++) {
console.log("Hello2")
if (fd[i].type === "image/jpeg" || fd[i].type === "image/jpg" || fd[i].type === "image/png" ){
console.log("Hello3")
const arrayBuffer = await promiseArrayBuffer(fd[i]);
var image = arrayBufferToBlob(arrayBuffer, fd[i].type)
var url = URL.createObjectURL(image);
let arrNew = printDrawingsRedux.imagesCounter.map((value, index) => {
if (index === i) {
return {...value} = {...value, link: url, drawingPages: {drawingSize: "А3 (297х420мм)",
kindPrintDrawing: "чорно-білий друк",
thicknessPaperDrawing: "80 г/щ",
commentForPage: "",
quantityDrawing: 1,
personalSize1: 0,
personalSize2: 0,
quantity: 1,
pageNotToPrint: false,
personalSizeCounter: function () {
return this.personalSize1 * this.personalSize2 / 1000000
},
} }
}else{
return value
}
})
dispatch(setImageCounterDrawingsRedux(arrNew))
}else {
console.log("pdf catched")
}
}})();
eventually have an empty array in Redux state instead of array with object
{id: index, link: false, quantity: 1,
type: value.type,
name: value.name,
blackWhitewRateCost: 50,
colorRateCost: 100,
drawingPages: [],
currentNumberPage: 1,
howManyPages: function () {
return this.drawingPages.length
},
modalPlusSize: false,
}
but if I delete part with async function it dispatch well, but with async function I finally get an empty array in state.
my action to this dispatch:
export const setImageCounterDrawingsRedux = (files) => {
return {
type: SET_IMAGECOUNTER_ASYNC_DRAWING,
payload: files,
}
}
my reducer:
case SET_IMAGECOUNTER_ASYNC_DRAWING:
return {...state, printDrawings: {...state.printDrawings, imagesCounter: action.payload} }

TypeError: Cannot read properties of undefined (reading 'add') in vuejs

Error is happening because of this line "word.classList.add('tag')". When i was first adding a class here "if (word.includes('#')) {}" i was getting the same error, so i thought i have to push words into new array and loop them again, but the problem is something else.
export default {
data() {
return {
tweets: [],
currentPage: 1,
numberOfPages: 0,
showPagination: 5,
newPage: 0,
text: [],
arrayOfWords: [],
}
},
methods: {
getTweets(newCurrent) {
this.tweets = []
const API_URL = `${this.$server}/api/twitter/tweets`
const params = {
token: getUserToken(),
page: this.$route.query.page,
newCurrentPage: newCurrent,
}
axios.post(API_URL, null, { params }).then(res => {
this.currentPage = res.data.page
this.numberOfPages = res.data.numberOfPages
res.data.tweets.forEach(tweet => {
const tweetData = {
id: tweet.id,
tweet_text: tweet.tweet_text,
twitter_name: tweet.twitter_name,
twitter_username: tweet.twitter_username,
added_at: moment(String(tweet.added_at)).format('MM/DD/YYYY hh:mm'),
}
this.tweets.push(tweetData)
this.text.push(tweet.tweet_text)
})
this.tweets.forEach(tweet => {
tweet.tweet_text.split(' ').forEach(word => {
if (word.includes('#')) {
this.arrayOfWords.push(word)
}
})
})
this.arrayOfWords.forEach(word => {
word.classList.add('tag')
console.log(word)
})
})
},
}
word is a string I think it has no classList, you can add classList to it if you like
word.classList = word.classList || []

[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'id' of undefined" in VueJS and Laravel

I have a table with the ability to add new items and edit existing ones (with the edit button being next to each entry). I have an issue with it whereby if you were to add a new item, NOT refresh the page, but then go to edit the item, it will edit it on Vue but not pass the edit back to the database. When you go to edit an item, the PUT URL returns a 404 error. If however, you refresh the page after adding an item, you can edit it perfectly fine. Any ideas what I've done wrong, or maybe forgotten to add? Same for the delete method too.
<script>
export default {
data: () => ({
dialog: false,
headers: [
{
text: 'Question',
align: 'left',
sortable: true,
value: 'question',
width: '25%'
},
{ text: 'Answer', value: 'answer', width: '55%' },
{ text: 'Actions', value: 'action', sortable: false, width: '20%' },
],
questions: [],
editedIndex: -1,
editedItem: {
question: '',
answer: ''
},
defaultItem: {
question: '',
answer: ''
},
}),
computed: {
formTitle () {
return this.editedIndex === -1 ? 'New Item' : 'Edit Item'
},
},
watch: {
dialog (val) {
val || this.close()
},
},
created () {
this.initialize();
this.loadUsers();
},
methods: {
initialize () {
this.questions = []
},
loadUsers(){
if (axios == null) {
return;
}
axios.get('/api/faq').then(res=>{
if(res.status === 200){
this.questions=res.data;
}
}).catch(err=>{
console.log(err);
});
},
editItem (item) {
this.editedIndex = this.questions.indexOf(item);
this.editedItem = Object.assign({}, item);
this.dialog = true
},
deleteItem (item) {
const index = this.questions.indexOf(item);
confirm('Are you sure you want to delete this item?') &&
axios.destroy('/api/faq/' + this.questions[this.editedIndex].id).then(response =>{
this.questions.splice(index, 1);
}).catch(error=>{
console.log('Deleting error')
})
},
close () {
this.dialog = false;
setTimeout(() => {
this.editedItem = Object.assign({}, this.defaultItem);
this.editedIndex = -1
}, 300)
},
saveToServer () {
if (this.editedIndex > -1) {
// Edit item
Object.assign(this.questions[this.editedIndex], this.editedItem);
axios.put('/api/faq/' + this.questions[this.editedIndex].id, this.editedItem).then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
} else {
//New item
this.questions.push(this.editedItem);
axios.post('/api/faq', this.editedItem).then(function (response) {
console.log('Before');
this.id = response.id;
console.log('After');
Object.assign(this.questions[this.editedIndex], this);
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
this.close()
},
},
}
</script>
Store Controller:
public function store(Request $request)
{
$id = faq::insertGetId($request->all());
return Response:: json([
'status' => 'ok',
'id' => $id,
], 200);
}
Update Controller:
public function update(Request $request, $id)
{
faq::findOrFail($id)->update($request->all());
return response(['message' => 'Success']);
}

React js add or remove state objects in an array with properties

I need to add or remove objects from the state.
State:
constructor(props) {
super(props);
this.state = {
scopesUser: [
{
scope: "user",
actions: ["create"]
},
{
scope: "make",
actions: ["create", "update", "delete"]
}
]
};
}
function:
onChangeScope = (scope, action, ev) => {
let event = ev.target.checked;
const { scopesUser } = this.state;
let copyScopes = Object.assign([], scopesUser);
console.log(scope, action, event, copyScopes);
let find = copyScopes.filter(obj => {
return obj.scope === scope;
});
let el = Object.assign({}, find[0]);
if (event === true) {
if (el.scope === undefined) {
console.log("creo");
this.setState(
prevState => ({
scopesUser: [...prevState.scopesUser, { scope, actions: [action] }]
}),
() => {
console.log(this.state.scopesUser);
}
);
} else {
console.log("modifico");
let actions = [...el.actions];
actions.push(action);
actions = actions
.reduce((a, b) => {
if (a.indexOf(b) < 0) a.push(b);
return a;
}, [])
.sort();
let index = copyScopes.findIndex(obj => obj.scope === scope);
copyScopes[index].actions = actions;
this.setState(
{
scopesUser: copyScopes
},
() => {
console.log(this.state.scopesUser);
}
);
}
} else {
let actions = [...el.actions];
actions = actions.filter(item => {
return item !== action;
});
if (actions.length === 0) {
let scop = copyScopes.filter(ul => {
return ul.scope != el.scope;
});
console.log("rem", el.actions.length);
this.setState(
{
scopesUser: scop
},
() => {
console.log(this.state.scopesUser);
}
);
} else {
let index = copyScopes.findIndex(obj => obj.scope === scope);
copyScopes[index].actions = actions;
this.setState(
{
scopesUser: copyScopes
},
() => {
console.log(this.state.scopesUser);
}
);
}
}
};
Add:
If the object does not exist, I add it to the state with the actions.
this.onChangeScope ("prop", "read", true);
scopesUser: [
...,
{
scope: "prop",
actions: ["read"]
}
]
If the object exists then I only add action to the object with the same name in the array.
this.onChangeScope ("make", "read", true);
scopesUser: [
...,
{
scope: "make",
actions: ["create", "read", "update", "delete"]
}
]
Remove:
If the object exists, I remove the actions property I passed, if the array is empty I remove the object from the state.
this.onChangeScope ("user", "create", true);
scopesUser: [
{
scope: "make",
actions: ["create", "update", "delete"]
}
]
I'm having some problems.
Can you give me some advice?
I hope, this is what you mean:
var object = {demonstration: "firstObject"};
object.added = {newObject: true};
object.remove = "This will be treated, as it would be removed";
object.remove = undefined;
console.log(object);
console.log(object.remove);
As you can see, you can just define the new state, to add an object.
I don't really know, how to remove Objects, but if you define it as undefined, that should work.
I hope, this is what you ment and it helps you

How to do a synchronous call with jaydata

I'm a bit confused about the asynchous call to the DataBase.
I just want to have a javasctipt adapter class for the calls to the web sql. But I'm not quite sure how to do this. Propably somebody have a good hint for me.
The function OfflneAppDBAdapter.prototype.IsDeviceConfigured() should return true or false depending if there are any items in the Table DeviceConfig.
function OfflneAppDBAdapter() {
self = this;
this.deviceIsConfigured = false;
this.Init = function () {
$data.Entity.extend("$de.offlineapp.DeviceConfig", {
Id: { type: "int", key: true, computed: true },
Name: { type: "string", required: true },
Token: { type: "string" },
Type: { type: "string" }
});
$data.EntityContext.extend("$de.offlineapp.DataContext", {
DeviceConfig: { type: $data.EntitySet, elementType: $de.offlineapp.DeviceConfig }
});
}
self.Init();
$de.offlineapp.context = new $de.offlineapp.DataContext({
name: "webSql", databaseName: "OfflineApp"
});
$de.offlineapp.context.onReady(function () {
});
}
// ************************************************************************
// PUBLIC METHODS -- ANYONE MAY READ/WRITE
// ************************************************************************
OfflneAppDBAdapter.prototype.AddDeviceConfig = function (deviceName, deviceToken, deviceTyp) {
$de.offlineapp.context.onReady(function () {
var promise = $de.offlineapp.context.DeviceConfig.toArray(function (x) {
if (x.length == 0) {
var emp = new $de.offlineapp.DeviceConfig({ Name: deviceName, Token: deviceToken, Type: deviceTyp });
$de.offlineapp.context.DeviceConfig.add(emp);
$de.offlineapp.context.saveChanges();
}
}
)
});
}
OfflneAppDBAdapter.prototype.IsDeviceConfigured = function () {
$de.offlineapp.context.onReady(function () {
var promise = $de.offlineapp.context.DeviceConfig.toArray(function (x) {
if (x.length == 0) {
this.deviceIsConfigured = true;
}
}
)
});
return this.deviceIsConfigured;
}
var myOfflineAppDBAdapter = new OfflneAppDBAdapter();
myOfflineAppDBAdapter.AddDeviceConfig("DeviceName", "Token", "iPad");
console.log(myOfflineAppDBAdapter.IsDeviceConfigured());
As expected the console prints "false". I' aware that the jaydata call works with callbacks and the callbacks are not part of the main class. But there must be a possibility to do so?
I would really apprechiate any help.
Thank you in advance....
Chris
UPDATE:
As you requested the startup code:
function OfflineApplication()
{
self = this;
}
OfflineApplication.prototype.StartApplication = function () {
//Check if online, then sync and
if (navigator && navigator.onLine === true) {
this.IsDeviceConfigured();
}
else {
}
}
///check if the device has a base configuration
OfflineApplication.prototype.IsDeviceConfigured = function () {
myOfflineAppDBAdapter.GetDeviceConfiguration(function (result) {
if (result.length > 0) {
myOfflineAppDBAdapter.deviceIsConfigured = true;
myOfflineApplication.HasDeviceAnApplication();
}
else {
///Get the device base conf from the server.
myOfflineAppSynchronisationAdapter.getDeviceConfigurationByToken(token, myOfflineApplication.HasDeviceAnApplication);
myOfflineAppDBAdapter.deviceIsConfigured = true;
}
});
}
///check if the device has an "application config" in general
OfflineApplication.prototype.HasDeviceAnApplication = function () {
myOfflineAppDBAdapter.GetDeviceAnApplication(function (result) {
if (result.length > 0) {
myOfflineApplication.IsDeviceApplicationVersionLatest(result);
}
else {
myOfflineApplication.GetApplication(false);
}
});
}
///the application config could differ from time to time, so we have to check if a different application should be synct with the device
OfflineApplication.prototype.IsDeviceApplicationVersionLatest = function (result) {
myOfflineAppDBAdapter.DeleteDeviceAnApplication(function () { });
console.log(result);
}
///get the application from the server
OfflineApplication.prototype.GetApplication = function (clearConfig) {
if (clearConfig === true)
{
}
myOfflineAppSynchronisationAdapter.getDeviceApplicationByToken(token, myOfflineApplication.LoadApplication);
}
OfflineApplication.prototype.LoadApplication = function () {
console.log('Now everything is finde and the application gets loaded..');
}
var myOfflineAppDBAdapter = new OfflneAppDBAdapter();
var myOfflineAppSynchronisationAdapter = new OfflineAppSynchronisationAdapter();
var myOfflineApplication = new OfflineApplication();
myOfflineApplication.StartApplication();
There is no sync way. You handling promises wrong. Make your code simple :) You'll need something like this:
$data.Entity.extend("$de.offlineapp.DeviceConfig", {
Id: { type: "int", key: true, computed: true },
Name: { type: "string", required: true },
Token: { type: "string" },
Type: { type: "string" }
});
$data.EntityContext.extend("$de.offlineapp.DataContext", {
DeviceConfig: { type: $data.EntitySet, elementType: $de.offlineapp.DeviceConfig }
});
var context = new $de.offlineapp.DataContext({
name: "webSql", databaseName: "OfflineApp"
});
function AddDeviceConfig(deviceName, deviceToken, deviceTyp) {
return context.DeviceConfig.toArray()
.then(function (x) {
if (x.length == 0) {
var emp = new $de.offlineapp.DeviceConfig({ Name: deviceName, Token: deviceToken, Type: deviceTyp });
context.DeviceConfig.add(emp);
return context.saveChanges();
}
})
}
function IsDeviceConfigured() {
return context.DeviceConfig.toArray()
.then(function (x) {
return x.length > 0;
})
}
context.onReady()
.then(IsDeviceConfigured)
.then(console.log)
.then(function() { return AddDeviceConfig("DeviceName", "Token", "iPad"); })
.then(IsDeviceConfigured)
.then(console.log);
here's a fiddle which does this: http://jsfiddle.net/JayData/cpT5q/1/

Categories