kendo ui mvvm: dynamically update multiselect datasource inside View Model' s change event - mvvm

I have a View with two multiselect widgets whose values (region_edu_admin, edu_admin) and datasources (region_edu_admins_ds, edu_admins_ds) are binded (through data-bind) to a ViewModel. Inside region_edu_admin's change event (regionEduAdminChanged) i am trying to reload edu_admin's widget datasource, that is edu_admins_ds, by using the set method. Though i do get inside newEduAdminsDS(), the datasource does not get reloaded. Any ideas on what i' m missing here would be much appreciated! You can see the code below:
/* View Model */
var LabsSearchVM = kendo.observable({
region_edu_admins_ds: newRegionEduAdminsDS(),
edu_admins_ds: newEduAdminsDS(),
region_edu_admin: "",
edu_admin: "",
regionEduAdminChanged: function(e) {
this.set("edu_admins_ds", newEduAdminsDS());
}
});
/* View */
<label for="region_edu_admin">Περιφερειακή Διεύθυνση Εκπαίδευσης</label>
<select id="sl_region_edu_admin"
name="region_edu_admin"
data-role="multiselect"
data-auto-bind="false"
data-value-primitive="true"
data-text-field="name"
data-value-field="name"
data-bind="source: region_edu_admins_ds, value: region_edu_admin, events: {change : regionEduAdminChanged }"
data-filter="contains"
multiple="multiple">
</select>
<label for="edu_admin">Διεύθυνση Εκπαίδευσης</label>
<select id="sl_edu_admin"
name="edu_admin"
data-role="multiselect"
data-auto-bind="false"
data-text-field="name"
data-value-field="name"
data-bind="source: edu_admins_ds, value: edu_admin"
data-filter="contains"
multiple="multiple">
</select>
/* newEduAdminsDS() function */
function newEduAdminsDS() {
var edu_admins_ds = new kendo.data.DataSource({
transport: {
read: {
url: "api/edu_admins",
type: "GET",
dataType: "json"
}
},
schema: {
data: "data",
model: {
id: "edu_admin_id",
fields: {
edu_admin_id: { editable: false },
name: { editable: false },
region_edu_admin_id: { editable: false },
region_edu_admin: { editable: false }
}
}
}
});
return edu_admins_ds;
}

You do not need to re-create the DataSource. All you need to do is tell it to read() again to reload the data. Change the regionEduAdminChanged function in your observable to this:
regionEduAdminChanged: function(e) {
this.edu_admins_ds.read();
}

Related

Bootstrap-vue: Auto-select first hardcoded <option> in <b-form-select>

I'm using b-form-select with server-side generated option tags:
<b-form-select :state="errors.has('type') ? false : null"
v-model="type"
v-validate="'required'"
name="type"
plain>
<option value="note" >Note</option>
<option value="reminder" >Reminder</option>
</b-form-select>
When no data is set for this field I want to auto-select the first option in the list.
Is this possible? I have not found how to access the component's options from within my Vue instance.
your v-model should have the value of the first option.
example
<template>
<div>
<b-form-select v-model="selected" :options="options" />
<div class="mt-3">Selected: <strong>{{ selected }}</strong></div>
</div>
</template>
<script>
export default {
data() {
return {
selected: 'a',
options: [
{ value: null, text: 'Please select an option' },
{ value: 'a', text: 'This is First option' },
{ value: 'b', text: 'Selected Option' },
{ value: { C: '3PO' }, text: 'This is an option with object value' },
{ value: 'd', text: 'This one is disabled', disabled: true }
]
}
}
}
</script>
You can trigger this.selected=${firstOptionValue} when no data is set.
what if we don't know what the first option is. The list is generated?
if you have dynamic data, something like this will work.
<template>
<div>
<b-form-select v-model="selected" :options="options" />
<div class="mt-3">Selected: <strong>{{ selected }}</strong></div>
</div>
</template>
<script>
export default {
data() {
return {
selected: [],
options: [],
};
},
mounted: function() {
this.getOptions();
},
methods: {
getOptions() {
//Your logic goes here for data fetch from API
const options = res.data;
this.options = res.data;
this.selected = options[0].fieldName; // Assigns first index of Options to model
return options;
},
},
};
</script>
If your options are stored in a property which is loaded dynamically:
computed property
async computed (using AsyncComputed plugin)
through props, which may change
Then you can #Watch the property to set the first option.
That way the behavior of selecting the first item is separated from data-loading and your code is more understandable.
Example using Typescript and #AsyncComputed
export default class PersonComponent extends Vue {
selectedPersonId: string = undefined;
// ...
// Example method that loads persons data from API
#AsyncComputed()
async persons(): Promise<Person[]> {
return await apiClient.persons.getAll();
}
// Computed property that transforms api data to option list
get personSelectOptions() {
const persons = this.persons as Person[];
return persons.map((person) => ({
text: person.name,
value: person.id
}));
}
// Select the first person in the options list whenever the options change
#Watch('personSelectOptions')
automaticallySelectFirstPerson(persons: {value: string}[]) {
this.selectedPersonId = persons[0].value;
}
}

Ember could not get select value from template to component

I'm struggling with this. I would like to pass a select value from template to component.
Here is my template
<select name="bank" class="form-control" id="sel1" onchange={{action "updateValue" value="bank"}}>
{{#each banks as |bank|}}
<option value={{bank.id}}>{{bank.name}}</option>
{{/each}}
{{log bank.id}}
</select>
And here is my component
import Ember from 'ember';
export default Ember.Component.extend({
store: Ember.inject.service('store'),
banks: Ember.computed(function() {
return this.get('store').findAll('bank');
}),
didUpdate() {
const banques = this.get('banks');
const hash = [];
banques.forEach(function(banque) {
hash.push(banque.get('name'));
});
Ember.$(".typeahead_2").typeahead({ source: hash });
},
actions: {
expand: function() {
Ember.$('.custom-hide').attr('style', 'display: block');
Ember.$('.custom-display').attr('style', 'display: none');
},
updateValue(selectedValue) {
this.set('bank.id', selectedValue);
},
login() {
console.log(this.get('bank.id'));
}
}
});
And i've got this beautiful error : Property set failed: object in path "bank" could not be found or was destroyed.
Any idea ? Thanks
When you use value attribute then you need to specify correct property name to be retrieved from the first argument(event). in your case you just mentioned bank - which was not found in event object. that's the reason for that error.
onchange={{action "updateValue" value="target.value"}}
inside component
updateValue(selectedValue) {
this.set('bank.id', selectedValue);
},

ag-Grid javaScript, TypeError: rowData is undefined

ag-Grid, following the official demo of javascript but using API like real world over hard-coded data. Note: no jQuery, just use the primitive plain XMLHttpRequest() for ajax.
F12 verified API returns data in the same structure as demo, has children node inside, and gripOptions.rowData is assigned with the returned data.
Tried instantiating rowData inside of gripOptions as
rowData: [], got the same error
Or
rowData: {}, got ReferenceError: rowData is not defined.
HTML:
<script src="/scripts/agGrid/ag-grid.js"></script>
<script src="/scripts/agGrid/myAG.js"></script>
<br />JavaScript ag-Grid
<div id="myGrid" style="height: 200px;" class="ag-fresh"></div>
myAG.js:
var httpApi = new XMLHttpRequest();
var columnDefs = [
{ headerName: "Client Name", field: "ClientName", unSortIcon: true, cellRenderer: "group" },
{ headerName: "Division", field: "Division" },
{ headerName: "Others", field: "Others" }
];
var gridOptions = {
columnDefs: columnDefs,
getNodeChildDetails: getNodeChildDetails
};
function getNodeChildDetails(rowItem) {
if (rowItem.ClientName) {
return {
group: true,
// provide ag-Grid with the children of this group
children: rowItem.children,
// the key is used by the default group cellRenderer
key: rowItem.ClientName
};
} else {
return null;
}
}
// wait for the document to be loaded, otherwise
// ag-Grid will not find the div in the document.
document.addEventListener("DOMContentLoaded", function () {
$.ajax({
type: "GET",
url: "/api/myAG/Tree",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
gridOptions.rowData = data;
var eGridDiv = document.querySelector('#myGrid');
new agGrid.Grid(eGridDiv, gridOptions);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
})
});
Version:
ag-grid = v8.1.0
FireFox = 50.1.0
Error message:
F12 confirms data exists and assigned:
inside of ag-grid.js, the line it complains about but rowData has data:
See this answered post, basically an additional check is needed for the tree.
ag-Grid, try to make Tree Demo work using own data

KendoUI: Unable to bind data to HTML elements from JSON file.

I am new to kendo ui and mvvm, and I'm facing this issue:
I'm having a JSON file in the follow format:
[
{
"Id":1,
"img":"shoes.png"},
{"Id":2,
"img":"books.png"}
}
]
I am reading the file using the sample mentioned online by kendo guys as follows:
var crudServiceBaseUrl = "pro.json";
var viewModel = kendo.observable({
productsSource: new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl,
dataType: "json"
},
update: {
url: crudServiceBaseUrl,
dataType: "json"
},
destroy: {
url: crudServiceBaseUrl,
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
return options;
}
},
batch: true,
schema: {
model: {
id: "Id"
}
}
})
});
kendo.bind($("#form-container"), viewModel);
I am able to bind the data from the data source to a Kendo Control such as a dropdownlist or some other Kendo Control. But when I try binding the data to an HTML Control (mostly an img tag). It stops working and gives an error saying "this.parent" is not a function.
following is the HTML which works:
Select Product: <select data-role="dropdownlist" data-value-field="Id" data-text-field="img"
data-bind="source: productsSource"></select>
However binding to a normal <img> tag does not work. In short I need to bind images based on src value to a div using kendo ui mvvm.
Kindly help me out. Thanks!!
-
Hardik
Currently Kendo MVVM cannot bind a data source to an HTML element. Only Kendo UI widgets can be bound to a kendo.data.DataSource. Using a widget e.g. the ListView would work for a DIV:
<div data-role="listview"
data-template="template"
data-bind="source: productsSource">
</div>
<script id="template" type="text/x-kendo-template">
<img data-bind="attr: { src: img }" />
</script>

Sencha touch 2 filterby() not updating records

I have a nested list on one of the pages of a Tabbed Panel app that is pulling data from "offices.json"
I should like to be able to filter this list when a user clicks on a toolbar button. However my filterBy() function doesn't update the store and the list of offices I can see, even though I can see in the console it is iterating the records and finding a match. What am I doing wrong?
(And yes I have tried doing s.load() both before and after the filterBy to no avail!)
toolbar:{
items:[{
text: 'Near you',
id: 'btnNearYou',
xtype: 'button',
handler: function() {
s = Ext.StoreMgr.get('offices');
s._proxy._url = 'officesFLAT.json';
console.log("trying to filter");
s.filterBy(function(record) {
var search = new RegExp("Altrincham", 'i');
if(record.get('text').match(search)){
console.log("did Match");
return true;
}else {
console.log("didnt Match");
return false;
}
});
s.load();
}
}]
For the record I'm defining my store like so:
store: {
type: 'tree',
model: 'ListItem',
id: 'offices',
defaultRootProperty: 'items',
proxy: {
type: 'ajax',
root: {},
url: 'offices.json',
reader: {
type: 'json',
rootProperty: 'items'
}
}
}
No need to recreate the regex each time, cache it outside.
You can simplify the code a lot (see below).
Why are you calling load directly after? That's going to send it to the server and it will just retrieve the same dataset.
toolbar: {
items: [{
text: 'Near you',
id: 'btnNearYou',
xtype: 'button',
handler: function() {
s = Ext.StoreMgr.get('offices');
s._proxy._url = 'officesFLAT.json';
var search = /Altrincham/i;
s.filterBy(function(record) {
return !!record.get('text').match(search);
});
}
}]
}