selectize.js and vue.js 2 ajax loaded optons - javascript

I'm using vuejs#2.3.3, selectize#0.12.4, vue2-selectize.
I have a pretty big form with a few select inputs.
All options are loaded by ajax into a one property, which is initialized with a demo data before being replaced by ajax data:
addTrackData : {
styles : [
{ id: 1, title: 'style 1' },
{ id: 2, title: 'style 3' },
{ id: 3, title: 'style 2' },
],
authors: [
{inn: '111', name: 'demo 1'},
{inn: '222', name: 'demo 2'},
{inn: '333', name: 'demo 3'}
]
....
},
And I've got 2 problems:
1) If I use settings in this way, options doesn't loads at all:
<selectize v-model="form.data.authors[i]['id']" :settings="selectize.authors"></selectize>
selectize: {
authors: {
valueField: 'inn',
labelField: 'name',
searchField: ['name', 'inn'],
options: this.addTrackData.authors // that doesn't works, but hard coded array works
}
}
Because of error Error in data(): "TypeError: Cannot read property 'authors' of undefined".
Both this.addTrackData.authors and addTrackData.authors makes this error.
But this way works:
<selectize v-model="form.data.authors[i]['id']"
:settings=" {
valueField: 'inn',
labelField: 'name',
searchField: ['name', 'inn'],
options: addTrackData.authors, // It works, but looks too ugly!
}" >
</selectize>
2) Options are not reactive - when ajax data comes, all selects elements still shows a demo data. And I have no idea how to update them all...
UPDATE
Second problem could be fixed with If Conditional and empty initial array:
<selectize v-if="addTrackData.authors.length" v-model="form.data.authors[i]['id']"
:settings=" {
valueField: 'inn',
labelField: 'name',
searchField: ['name', 'inn'],
options: addTrackData.authors, // It works, but looks too ugly!
}" >
</selectize>
addTrackData : {
styles : [],
authors: []
....
}
But the first problem still makes me cry

I just read the source code of vue2-selectize and noticed that it's watch code for options key is incorrect.
his code is this way:
watch: {
value() {
this.setValue()
},
options (value, old) {
if (this.$el.selectize && !equal(value, old)) {
this.$el.selectize.clearOptions()
this.$el.selectize.addOption(this.current)
this.$el.selectize.refreshOptions(false)
this.setValue()
}
}
},
while it should be this way to work:
watch: {
value() {
this.setValue()
},
options (value, old) {
if (this.$el.selectize && !equal(value, old)) {
this.$el.selectize.clear();
this.$el.selectize.clearOptions();
var vm = this;
this.$el.selectize.load(function(callback) {
callback(vm.current);
});
this.$el.selectize.refreshOptions(false);
this.setValue();
}
}
},
I just prepared a hacky way to make it working but I dont encourage you using it in production.
Here is the fiddle's link: https://jsfiddle.net/ahmadm/h8p97hm7/
I'll try to send a pull request to his creator as soon as possible but until that time, your solution is already the only possible solution.

Related

Document.getElementsByClassName has 0 length but has elements inside

[![Firefox Console][1]][1]In my Vue app I am trying to use mdb-datatable, the table reads data() and sets the rows accordingly. I am setting the row data programmatically after my data is loaded with Ajax. In one column I need to add a button and it needs to call a function. I am trying to add onclick function to all buttons with "status-button" class but something weird happens.
When I print HtmlCollection it has a button inside, which is expected but I can't reach proceedButtons[0], it is undefined. proceedButtons.length also prints 0 length but I see the button in console.
I also tried to add onclick function but probably "this" reference changes and I get errors like "proceedStatus is not a function" it does not see anything from outer scope.
<mdb-datatable
:data="tableData"
:searching="false"
:pagination="false"
:responsive="true"
striped
bordered/>
export default {
name: "Applications",
mixins: [ServicesMixin, CommonsMixin],
components: {
Navbar,
Multiselect,
mdbDatatable
},
data () {
return {
statusFilter: null,
searchedWord: '',
jobRequirements: [],
applications: [],
options: ['Awaiting', 'Under review', 'Interview', 'Job Offer', 'Accepted'],
tableData: {
columns: [
{
label: 'Name',
field: 'name',
sort: 'asc',
},
{
label: 'Date',
field: 'date',
sort: 'asc'
},
{
label: 'Compatibility',
field: 'compatibility',
sort: 'asc'
},
{
label: 'Status',
field: 'status',
sort: 'asc'
},
{
label: 'Proceed Application Status',
field: 'changeStatus',
}
],
rows: []
}
}
}
fillTable(applications) {
let statusButtonId = 0;
applications.forEach(application => {
this.tableData.rows.push({
name: application.candidateLinkedIn.fullName,
date: this.parseDateFromDateObject(application.applicationDate),
compatibility: this.calculateJobCompatibility(application.candidateLinkedIn.linkedInSkillSet),
status: application.applicationStatus,
changeStatus: '<button type="button" class="btn-indigo btn-sm m-0 status-button"' +
' style="margin-left: 1rem">' +
'Proceed Status</button>',
candidateSkillSet: application.candidateLinkedIn.linkedInSkillSet
});
statusButtonId++;
});
},
addEventListenersToButtons() {
let proceedButtons = document.getElementsByClassName("status-button")
console.log(proceedButtons);
console.log(proceedButtons[0])
console.log(proceedButtons.item(0))
/*
proceedButtons.forEach(button => {
button.addEventListener("click",this.proceedStatus);
});
*/
},
[1]: https://i.stack.imgur.com/zUplv.png
From MDN:
Get the first element with a class of 'test', or undefined if there is no matching element:
document.getElementsByClassName('test')[0]
So undefined means no match, even if length is 0...
Since this is not an array, you do not get out-of-bounds exceptions.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
Regarding Arrays
You can't index the list returned from getElementsByClassName.
You can turn it into an array though, and then index it.
ES6
let proceedButtons = document.getElementsByClassName("status-button")
const arr = Array.from(proceedButtons);
console.log(arr[0]);
Old School
const arr = []
Array.prototype.forEach.call(proceedButtons, function(el) {
arr.push(el);
});
console.log(arr[0]);

bootstrap-vue - table won't get updated after AJAX request (vue2.js)

I'm pretty new with vue.js and I saw this great library that doing exactly what I need for my project: Boostrap-Vue
example source code
I followed the basic instructions and I've added an small change, ajax call for dynamic content:
<layout :docs="docs">
<template slot="demo">
<b-table
stripped
hover
:items="items"
:fields="fields"
:current-page="currentPage"
:per-page="perPage"
:filter="filter"
>
<template slot="name" scope="item">
{{item.value.first}} {{item.value.last}}
</template>
</b-table>
</template>
</layout>
export default {
mounted () {
this.get_data();
},
data() {
return {
docs: {
component: 'bTable'
},
items: [],
fields: {
name: {label: 'Person Full name', sortable: true},
},
currentPage: 1,
perPage: 5,
filter: null
};
},
methods: {
get_data () {
this.$http.get("myapp/users").then(res => {
if (res.body) {
this.items = res.body;
} else {
this.error = true;
}
});
}
}
};
So the problem is - after I'm getting the Ajax response and the "items" variable initialized with the data but the table still won't get update.
The strangest part is that with static data its works fine (as shown in the example source code, without AJAX).
Any idea why?
Thanks!!!
I found the problem, it seems that it necessary to define the following fields according to the value I received in the response:
fields: {
name: {label: 'Person Full name', sortable: true},
}
so if my json looks like this:
{user_name: "user"}
it should look like this:
fields: {
user_name: {label: 'Person Full name', sortable: true},
}
Anyway, Yoram de Langen Thanks for the help!
Did you try to debug the res.body and what it contains? What is the structure your myapp/users returns? Do you return the structure directly like so:
[
{ "name": "item 1"},
{ "name": "item 1"},
]
or does it look like this:
{
"result": [
{ "name": "item 1"},
{ "name": "item 1"},
]
}
In case of the latest one your this.items = res.body should be: this.items = res.body.result

Updating entire dojox.grid.datagrid row

I've been trying to update the entire row of my grid, but having issues. I am able to update a single cell (if it doesn't have a formatter), but I would like to be able to update the entire row. Alternatively, I could update the column, but I'm not able to get it working if it has a formatter.
Here is the code that I'm using to update the grid:
grid.store.fetch({query : { some_input : o.some_input },
onItem : function (item ) {
dataStore.setValue(item, 'input', '123'); //works!
dataStore.setValue(item, '_item', o); //doesn't work!
}
});
And the structure of my grid:
structure: [
{ type: "dojox.grid._CheckBoxSelector"},
[[{ name: "Field1", field: "input", width:"25%"}
,{ name: "Field2", field: "another_input", width:"25%"}
,{ name: "Field3", field: "_item", formatter:myFormatter, width:"25%"}
,{ name: "Field4", field: "_item", formatter:myOtherFormatter, width:"25%"}
]]
]
Got some information in the #dojo freenode channel from 'tk' who kindly put together a fiddle showing the proper way to do this, most noteably putting an idProperty on the memoryStore and overwriting the data: http://jsfiddle.net/few3k7b8/2/
var memoryStore = new Memory({
data: [{
alienPop: 320000,
humanPop: 56000,
planet: 'Zoron'
}, {
alienPop: 980940,
humanPop: 56052,
planet: 'Gaxula'
}, {
alienPop: 200,
humanPop: 500,
planet: 'Reiutsink'
}],
idProperty: "planet"
});
And then when we want to update:
memoryStore.put(item, {
overwrite: true
});
Remember that item has to have a field 'planet', and it should be the same as one of our existing planets in order to overwrite that row.

Programmatically Set Constructor Parameters in Javascript

I am trying to interact with a javascript api (bare in mind I have never done this before). An example of what I am attempting to work with is here:
SearchSpring.Catalog.init({
leaveInitialResults : true,
facets : '.leftNav',
results : '#results',
result_layout: 'list',
results_per_page : 12,
layout: 'top',
loadCSS: false,
filters: {
color: ['Blue']
},
backgroundFilters: {
category: ['Shirt', 'Shoes'],
department: ['Mens']
},
maxFacets: 5,
maxFacetOptions: 10,
sortText: 'Sort By ',
sortType: 'dropdown',
filterText: 'Refine Search Results',
previousText: 'Previous',
scrollType: 'scroll',
scrollTo: 'body',
backgroundSortField: 'price',
backgroundSortDir: 'desc',
compareText: 'Compare Items',
summaryText: 'Current Filters',
showSummary: true,
subSearchText: 'Subsearch:',
showSubSearch: true,
forwardSingle: false,
afterResultsChange: function() { $('.pagination').hide(); },
filterData: function(data) { console.debug(data); }
});
In the example I want to add a "backgroundFilter" to this with a value:
var cat="MyNewCategory";
cat.value="ANewValue;
How would I add this category and value to the backgroundFilters: listed above?
This is a very common framework initialization pattern when working with frameworks.
Your example code is passing a JavaScript Object {} as a parameter into a function () that is called init.
Taking out all definitions the pattern looks like this:
SomeFramework.frameworkFunction({});
In the above code the {} is an empty object used for initialization. There are two ways that you can work with that object in practice.
Regarding your first code snippet, you can add code into that 'object literal'.
backgroundFilters: {
category: ['Shirt', 'Shoes'],
department: ['Mens'],
cat: ['My value']
},
Notice the added comma, this is an important tripping point. This may or may not fit your needs, depending on a few factors.
Regarding your second code snippet, you can apply members to JavaScript objects at runtime. What I mean is, your var cat can be added to the anonymous object-literal that is being passed in. Hard to say, but a simple concept. Here is how:
//Say this is initialized in some separate way. //There is a bug here I'll describe later.
var cat="MyNewCategory";
cat.value="ANewValue";
//Extract and name the initialization object. It is verbatim at this point.
var initObject = {
leaveInitialResults : true,
facets : '.leftNav',
results : '#results',
result_layout: 'list',
results_per_page : 12,
layout: 'top',
loadCSS: false,
filters: {
color: ['Blue']
},
backgroundFilters: {
category: ['Shirt', 'Shoes'],
department: ['Mens']
},
maxFacets: 5,
maxFacetOptions: 10,
sortText: 'Sort By ',
sortType: 'dropdown',
filterText: 'Refine Search Results',
previousText: 'Previous',
scrollType: 'scroll',
scrollTo: 'body',
backgroundSortField: 'price',
backgroundSortDir: 'desc',
compareText: 'Compare Items',
summaryText: 'Current Filters',
showSummary: true,
subSearchText: 'Subsearch:',
showSubSearch: true,
forwardSingle: false,
afterResultsChange: function() { $('.pagination').hide(); },
filterData: function(data) { console.debug(data); }
};
//Now we can add variables (and functions) dynamically at runtime.
initObject.cat = cat;
//And pass them into the framework initialization in a separated way.
SearchSpring.Catalog.init(initObject);
Now for the bug. I don't know the solution because I do not know what it is intended to do, but I can point out what is potentially incorrect.
var cat="MyNewCategory";
cat.value="ANewValue;
This code is: 1 creating a String Object called cat. 2 changing the value to a new string.
I do not think this is what you really want.
To add a new backgroundFilter, in the separated way above, it would be:
initObject.backgroundFilters.cat = ['A', 'B'];
//Line above would give you this type of definition within the initObject (at runtime):
backgroundFilters: {
category: ['Shirt', 'Shoes'],
department: ['Mens'],
cat: ['A','B']
},
For this to work it will depend on what the framework is expecting regarding backgroundFilters.
Hope that helps.
All the best!
Nash
I don't quite understand - do you want to have the backgroundFilters categories as structured objects rather than plain strings? If you are in control of the entire API, you can do something like
...
backgroundFilters: {
category: [
new SearchSpring.Catalog.Category("Shirt"),
new SearchSpring.Catalog.Category("Shoes"),
new SearchSpring.Catalog.Category("MyNewCategory", "ANewValue")
],
department: 'Mens'
}
...

Adding items dynamically from javascript array in Sencha Touch

I have this code
var filter = {
items: [{
xtype: 'fieldset',
title: 'Choose',
items: [
// I need to put checkboxes here
]
}]
};
I need to dynamically add checkbox items:
{
xtype: 'checkboxfield',
name: 'city[]',
label: 'City name',
checked: false,
}
The data that I need to add is stored in JS array, and checkbox can be checked or unchecked
Please help,
Thank you in advance
What is your issue? When do you add? What is the event?
filter.items[0].items[filter.items[0].items.length] = {
xtype: 'checkboxfield',
name: 'city[]',
label: 'City name',
checked: false,
}
or
var checkbox = {
xtype: 'checkboxfield',
name: 'city[]',
label: 'City name',
checked: false,
}
var itemArr = filter.items[0].items;
itemArr[itemArr.length]=checkbox;
What is filter, is it a Container or does it extend from it (Panel, FormPanel, etc.)?
If so, you can use the add() method to dynamically add to it.
It's also good to note, that posting in the Sencha Forums will get your a much faster response.

Categories