I'm doing a JS script which will render a tree view with picking abilities.
But something strange is happening and i found out what it was, however this doesn't make me happy and i want to discover why it's happening.
var picker1 = {},
picker2 = {};
(function($) {
$.fn.treePicker = function(params) {
var exists = $(this).length > 0;
if (exists) {
params.controlDiv = $(this);
var picker = new treePicker(params);
return picker;
}
};
var treePicker = function(params) {
this.mapping.id = params.mapping.id; // Change to this.mapping = params.mapping;
};
$.extend(treePicker.prototype, {
mapping: {
id: 'id',
text: 'text',
},
});
var picker1 = $("#render1").treePicker({
mapping: {
id: 'Id1',
text: 'text1'
}
});
var picker2 = $("#render2").treePicker({
mapping: {
id: 'Id2',
text: 'text2'
}
});
$("#result1").val(picker1.mapping.id + "," + picker1.mapping.text);
$("#result2").val(picker2.mapping.id + "," + picker2.mapping.text);
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="result1" />
<input type="text" id="result2" />
<div id="render1"></div>
<div id="render2"></div>
I've two divs where the controls will be rendered.
To this demo I've two inputs where i show the pickers data.
I'm setting the property picker1.mapping.id and picker1.mapping.text (line 24-29) to match id1 and text1.
var picker1 = $("#render1").treePicker({
mapping: {
id: 'Id1',
text: 'text1'
}
});
Then, I'm setting the same properties to picker2 (line 31-36).
My "constructor" is located on
var treePicker = function (params) {
this.mapping.id = params.mapping.id; // Change to this.mapping.id = params.mapping.id
};
And I'm extending the "class" doing this:
$.extend(treePicker.prototype, {
mapping: {
id: 'id',
text: 'text',
},
});
The problem is that while doing this, picker1.mapping.id will not keep his own value and instead will hold picker2 value.
But... if I change
this.mapping.id = params.mapping.id;
to
this.mapping = params.mapping;
It will work.
Any ideas?
Related
I have a JS object:
var bookmark = {
id: 'id',
description: 'description',
notes: 'notes'
}
I want to bind to the entire object, display notes in a textarea, and subscribe to changes to notes.
Here's what I have so far:
this.bookmark = ko.observable();
this.bookmark.subscribe = function(bookmarkWithNewNotes) {
//use the bookmarkWithNewNotes.id to update the bookmark in the db
}
I'm setting the bookmark like so:
this.bookmark(ko.mapping.fromJS(existingBookmark));
The view looks like this:
<div databind="with: $root.bookmark" >
Notes
<textarea class="userNotes" rows="10" data-bind="value: notes" ></textarea>
</div>
This isn't working. What do I need to do to make this work the way I want it to work?
Thanks!
Here is a example in Fiddle.
You could do something like this:
<div>
Notes
<div data-bind="foreach: bookmarks">
<textarea rows="10" data-bind="value: note"></textarea>
</div>
</div>
and create viewmodel for your bookmark, like so:
function BookmarkViewModel(id, description, note) {
var self = this;
self.id = id;
self.description = ko.observable(description);
self.note = ko.observable(note);
self.note.subscribe(function(val) {
alert("Save note, id: " + self.id + ", description: " + self.description() + ", note: " + self.note());
});
return self;
}
after you get your data, create VM for every item, like so:
function AppViewModel(data) {
var self = this;
self.bookmarks = ko.observableArray();
for (var i = 0; i < data.length; i++) {
self.bookmarks().push(new BookmarkViewModel(data[i].id, data[i].description, data[i].note));
};
return self;
}
You can create a seperate service to get your data, i just mocked this for poc.
$(function() {
var data = [{
id: 1,
description: 'some description',
note: 'some note'
}, {
id: 2,
description: 'some other description',
note: 'some other note'
}];
ko.applyBindings(new AppViewModel(data));
});
I am not very good with my javascript but recently needed to work with a library to output an aggregated table. Was using fin-hypergrid.
There was a part where I need to insert a sum function (rollups.sum(11) in this example)to an object so that it can compute an aggregated value in a table like so:
aggregates = {Value: rollups.sum(11)}
I would like to change this value to return 2 decimal places and tried:
rollups.sum(11).toFixed(2)
However, it gives the error : "rollups.sum(...).toFixed is not a function"
If I try something like:
parseFloat(rollups.sum(11)).toFixed(2)
it throws the error: "can't assign to properties of (new String("NaN")): not an object"
so it has to be a function object.
May I know if there is a way to alter the function rollups.sum(11) to return a function object with 2 decimal places?
(side info: rollups.sum(11) comes from a module which gives:
sum: function(columnIndex) {
return sum.bind(this, columnIndex);
}
)
Sorry I could not post sample output here due to data confidentiality issues.
However, here is the code from the example I follow. I basically need to change rollups.whatever to give decimal places. The "11" in sum(11) here refers to a "column index".
window.onload = function() {
var Hypergrid = fin.Hypergrid;
var drillDown = Hypergrid.drillDown;
var TreeView = Hypergrid.TreeView;
var GroupView = Hypergrid.GroupView;
var AggView = Hypergrid.AggregationsView;
// List of properties to show as checkboxes in this demo's "dashboard"
var toggleProps = [{
label: 'Grouping',
ctrls: [
{ name: 'treeview', checked: false, setter: toggleTreeview },
{ name: 'aggregates', checked: false, setter: toggleAggregates },
{ name: 'grouping', checked: false, setter: toggleGrouping}
]
}
];
function derivedPeopleSchema(columns) {
// create a hierarchical schema organized by alias
var factory = new Hypergrid.ColumnSchemaFactory(columns);
factory.organize(/^(one|two|three|four|five|six|seven|eight)/i, { key: 'alias' });
var columnSchema = factory.lookup('last_name');
if (columnSchema) {
columnSchema.defaultOp = 'IN';
}
//factory.lookup('birthState').opMenu = ['>', '<'];
return factory.schema;
}
var customSchema = [
{ name: 'last_name', type: 'number', opMenu: ['=', '<', '>'], opMustBeInMenu: true },
{ name: 'total_number_of_pets_owned', type: 'number' },
{ name: 'height', type: 'number' },
'birthDate',
'birthState',
'employed',
{ name: 'income', type: 'number' },
{ name: 'travel', type: 'number' }
];
var peopleSchema = customSchema; // or try setting to derivedPeopleSchema
var gridOptions = {
data: people1,
schema: peopleSchema,
margin: { bottom: '17px' }
},
grid = window.g = new Hypergrid('div#json-example', gridOptions),
behavior = window.b = grid.behavior,
dataModel = window.m = behavior.dataModel,
idx = behavior.columnEnum;
console.log('Fields:'); console.dir(behavior.dataModel.getFields());
console.log('Headers:'); console.dir(behavior.dataModel.getHeaders());
console.log('Indexes:'); console.dir(idx);
var treeView, dataset;
function setData(data, options) {
options = options || {};
if (data === people1 || data === people2) {
options.schema = peopleSchema;
}
dataset = data;
behavior.setData(data, options);
idx = behavior.columnEnum;
}
// Preset a default dialog options object. Used by call to toggleDialog('ColumnPicker') from features/ColumnPicker.js and by toggleDialog() defined herein.
grid.setDialogOptions({
//container: document.getElementById('dialog-container'),
settings: false
});
// add a column filter subexpression containing a single condition purely for demo purposes
if (false) { // eslint-disable-line no-constant-condition
grid.getGlobalFilter().columnFilters.add({
children: [{
column: 'total_number_of_pets_owned',
operator: '=',
operand: '3'
}],
type: 'columnFilter'
});
}
window.vent = false;
//functions for showing the grouping/rollup capabilities
var rollups = window.fin.Hypergrid.analytics.util.aggregations,
aggregates = {
totalPets: rollups.sum(2),
averagePets: rollups.avg(2),
maxPets: rollups.max(2),
minPets: rollups.min(2),
firstPet: rollups.first(2),
lastPet: rollups.last(2),
stdDevPets: rollups.stddev(2)
},
groups = [idx.BIRTH_STATE, idx.LAST_NAME, idx.FIRST_NAME];
var aggView, aggViewOn = false, doAggregates = false;
function toggleAggregates() {
if (!aggView){
aggView = new AggView(grid, {});
aggView.setPipeline({ includeSorter: true, includeFilter: true });
}
if (this.checked) {
grid.setAggregateGroups(aggregates, groups);
aggViewOn = true;
} else {
grid.setAggregateGroups([], []);
aggViewOn = false;
}
}
function toggleTreeview() {
if (this.checked) {
treeView = new TreeView(grid, { treeColumn: 'State' });
treeView.setPipeline({ includeSorter: true, includeFilter: true });
treeView.setRelation(true, true);
} else {
treeView.setRelation(false);
treeView = undefined;
delete dataModel.pipeline; // restore original (shared) pipeline
behavior.setData(); // reset with original pipeline
}
}
var groupView, groupViewOn = false;
function toggleGrouping(){
if (!groupView){
groupView = new GroupView(grid, {});
groupView.setPipeline({ includeSorter: true, includeFilter: true });
}
if (this.checked){
grid.setGroups(groups);
groupViewOn = true;
} else {
grid.setGroups([]);
groupViewOn = false;
}
}
you may try:
(rollups.sum(11)).toFixed(2)
enclosing number in parentheses seems to make browser bypass the limit that identifier cannot start immediately after numeric literal
edited #2:
//all formatting and rendering per cell can be overridden in here
dataModel.getCell = function(config, rendererName) {
if(aggViewOn)
{
if(config.columnName == "total_pets")
{
if(typeof(config.value) == 'number')
{
config.value = config.value.toFixed(2);
}
else if(config.value && config.value.length == 3 && typeof(config.value[1]) == 'number')
{
config.value = config.value[1].toFixed(2);
}
}
}
return grid.cellRenderers.get(rendererName);
};
In knockout JS I want to find out 1st duplicate object from my collection and return that object as modal. I have to check for 1st duplicate object from first array aginst 2nd Array based on my condition. Tried _findWhere & _.Some & _.each nothing worked. Can someone help
Here -- MyMainModal is my Moda which will have multiple objects
self.dupRecord= function (MyMainModal) {
var Modaldata= ko.mapping.toJS(MyMainModal);
return _.some(Modaldata, function (MD1) {
return _.some(Modaldata, function (MD2) {
if ((MD1.ID!== MD2.Id) &&
(MD1.Name === MD2.name));
});
});
};
How about incorporating the check for first duplicate into the mapping? Something like:
function Child(data) {
ko.mapping.fromJS(data, {}, this);
};
var model = {
children: [{
id: '1',
name: 'Billy'
}, {
id: '2',
name: 'Susy'
}]
};
var mapping = {
children: {
key: function(data) {
return ko.utils.unwrapObservable(data.id);
},
create: function(options) {
console.log('creating ' + options.data.name, options.parent);
var newChild = new Child(options.data);
if(options.parent.firstDuplicate() === undefined)
options.parent.children().forEach(function(child) {
if(child.name() === newChild.name())
options.parent.firstDuplicate([child, newChild]);
});
return newChild;
},
update: function(options) {
console.log(' updating ' + options.data.name);
return options.target;
}
}
};
var vm = {
children: ko.observableArray(),
firstDuplicate: ko.observable()
};
ko.mapping.fromJS(model, mapping, vm);
ko.applyBindings(vm);
model.children.push({
id: 3,
name: 'Billy'
});
setTimeout(function() {
console.log('--remapping--');
ko.mapping.fromJS(model, mapping, vm);
}, 2000);
I read that as, "if we're not updating the record, potentially set the first duplicate." Here's a fiddle: http://jsfiddle.net/ge1abt6a/
I'm starting to learn and azure phonejs.
Todo list get through a standard example:
$(function() {
var client = new WindowsAzure.MobileServiceClient('https://zaburrito.azure-mobile.net/', 'key');
var todoItemTable = client.getTable('todoitem');
// Read current data and rebuild UI.
// If you plan to generate complex UIs like this, consider using a JavaScript templating library.
function refreshTodoItems() {
var query = todoItemTable.where({ complete: false });
query.read().then(function(todoItems) {
var listItems = $.map(todoItems, function(item) {
return $('<li>')
.attr('data-todoitem-id', item.id)
.append($('<button class="item-delete">Delete</button>'))
.append($('<input type="checkbox" class="item-complete">').prop('checked', item.complete))
.append($('<div>').append($('<input class="item-text">').val(item.text)));
});
$('#todo-items').empty().append(listItems).toggle(listItems.length > 0);
$('#summary').html('<strong>' + todoItems.length + '</strong> item(s)');
}, handleError);
}
function handleError(error) {
var text = error + (error.request ? ' - ' + error.request.status : '');
$('#errorlog').append($('<li>').text(text));
}
function getTodoItemId(formElement) {
return $(formElement).closest('li').attr('data-todoitem-id');
}
// Handle insert
$('#add-item').submit(function(evt) {
var textbox = $('#new-item-text'),
itemText = textbox.val();
if (itemText !== '') {
todoItemTable.insert({ text: itemText, complete: false }).then(refreshTodoItems, handleError);
}
textbox.val('').focus();
evt.preventDefault();
});
// Handle update
$(document.body).on('change', '.item-text', function() {
var newText = $(this).val();
todoItemTable.update({ id: getTodoItemId(this), text: newText }).then(null, handleError);
});
$(document.body).on('change', '.item-complete', function() {
var isComplete = $(this).prop('checked');
todoItemTable.update({ id: getTodoItemId(this), complete: isComplete }).then(refreshTodoItems, handleError);
});
// Handle delete
$(document.body).on('click', '.item-delete', function () {
todoItemTable.del({ id: getTodoItemId(this) }).then(refreshTodoItems, handleError);
});
// On initial load, start by fetching the current data
refreshTodoItems();
});
and it works!
Changed for the use of phonejs and the program stops working, even mistakes does not issue!
This my View:
<div data-options="dxView : { name: 'home', title: 'Home' } " >
<div class="home-view" data-options="dxContent : { targetPlaceholder: 'content' } " >
<button data-bind="click: incrementClickCounter">Click me</button>
<span data-bind="text: listData"></span>
<div data-bind="dxList:{
dataSource: listData,
itemTemplate:'toDoItemTemplate'}">
<div data-options="dxTemplate:{ name:'toDoItemTemplate' }">
<div style="float:left; width:100%;">
<h1 data-bind="text: name"></h1>
</div>
</div>
</div>
</div>
This my ViewModel:
Application1.home = function (params) {
var client = new WindowsAzure.MobileServiceClient('https://zaburrito.azure-mobile.net/', 'key');
var todoItemTable = client.getTable('todoitem');
var toDoArray = ko.observableArray([
{ name: "111", type: "111" },
{ name: "222", type: "222" }]);
var query = todoItemTable.where({ complete: false });
query.read().then(function (todoItems) {
for (var i = 0; i < todoItems.length; i++) {
toDoArray.push({ name: todoItems[i].text, type: "NEW!" });
}
});
var viewModel = {
listData: toDoArray,
incrementClickCounter: function () {
todoItemTable = client.getTable('todoitem');
toDoArray.push({ name: "Zippy", type: "Unknown" });
}
};
return viewModel;
};
I can easily add items to the list of programs, but from the server list does not come:-(
I am driven to exhaustion and can not solve the problem for 3 days, which is critical for me!
Specify where my mistake! Thank U!
I suggest you use a DevExpress.data.DataSource and a DevExpress.data.CustomStore instead of ko.observableArray.
Application1.home = function (params) {
var client = new WindowsAzure.MobileServiceClient('https://zaburrito.azure-mobile.net/', 'key');
var todoItemTable = client.getTable('todoitem');
var toDoArray = [];
var store = new DevExpress.data.CustomStore({
load: function(loadOptions) {
var d = $.Deferred();
if(toDoArray.length) {
d.resolve(toDoArray);
} else {
todoItemTable
.where({ complete: false })
.read()
.then(function(todoItems) {
for (var i = 0; i < todoItems.length; i++) {
toDoArray.push({ name: todoItems[i].text, type: "NEW!" });
}
d.resolve(toDoArray);
});
}
return d.promise();
},
insert: function(values) {
return toDoArray.push(values) - 1;
},
remove: function(key) {
if (!(key in toDoArray))
throw Error("Unknown key");
toDoArray.splice(key, 1);
},
update: function(key, values) {
if (!(key in toDoArray))
throw Error("Unknown key");
toDoArray[key] = $.extend(true, toDoArray[key], values);
}
});
var source = new DevExpress.data.DataSource(store);
// older version
store.modified.add(function() { source.load(); });
// starting from 14.2:
// store.on("modified", function() { source.load(); });
var viewModel = {
listData: source,
incrementClickCounter: function () {
store.insert({ name: "Zippy", type: "Unknown" });
}
};
return viewModel;
}
You can read more about it here and here.
I'm relatively new to Ember and JS frameworks and I'm facing difficulty in connecting a model to the Ember Table view/component.
With the code I currently have, the table is rendering but the rows are not being populated with any data. Obviously, I'm doing something wrong and falling short of understanding how to make this work properly.
I have tried to implement something similar to the technique used here and here but can't get it to work.
I wanted to use the FixtureAdapter to populate the model with data for now but later on move to retrieving the data from my backend API via Ajax/JSON.
Any help is greatly appreciated.
The JS part:
window.App = Ember.Application.create({
LOG_TRANSITIONS: true,
LOG_TRANSITIONS_INTERNAL: true,
LOG_VIEW_LOOKUPS: true,
// LOG_ACTIVE_GENERATION: true,
LOG_BINDINGS: true
});
var stringAttr = DS.attr('string');
App.Item = DS.Model.extend({
name: stringAttr,
desc: stringAttr,
category: DS.attr('number'),
tags: stringAttr,
note: stringAttr
});
App.Item.FIXTURES = [
{ id: 0, name: 'XY Laptop', desc: 'test laptop', category: 1, tags: 'computers, laptops', note:"note"},
{ id: 1, name: 'ZZ Computer', desc: 'super computer!', category: 0, tags: 'computers', note:"note"},
{ id: 2, name: 'MM Radio', desc: 'FM Radio', category: 1, tags: 'radios, recorders', note:"note"}
];
App.Router.map(function() {
this.resource('inventory', function() {
this.resource('items', function() {
this.resource('item', { path: ':item_id' }, function() {
this.route('edit');
});
});
});
});
// Temporary buffer object that sites between Ember Table and the model object (the Item model object)
App.RowProxy = Ember.Object.extend({
object: null,
getObjectProperty: function(prop) {
var obj = this.get('object');
if(obj) { console.log(prop + " : " + obj.get(prop)); }
return obj ? obj.get(prop) : 'Loading ...';
},
isLoaded: function() { return !!this.get('object'); }.property('object'),
id: function() { return this.getObjectProperty('id'); }.property('object.id'),
name: function() { return this.getObjectProperty('name'); }.property('object.name'),
desc: function() { return this.getObjectProperty('desc'); }.property('object.desc'),
category: function() { return this.getObjectProperty('category'); }.property('object.category'),
tags: function() { return this.getObjectProperty('tags'); }.property('object.tags'),
note: function() { return this.getObjectProperty('note'); }.property('object.note')
});
App.LazyDataSource = Ember.ArrayProxy.extend({
requestPage: function(page) {
var content, end, start, url, _i, _results;
content = this.get('content');
start = (page - 1) * 3;
end = start + 3;
// find items and then update the RowProxy to hold the item object.
this.get('store').find('item').then(function(items) {
return items.forEach(function(item, index) {
var position = start + index;
content[position].set('object', item);
});
});
// fill the 'content' array with RowProxy objects
return (function() {
_results = [];
for (var _i = start; start <= end ? _i < end : _i > end; start <= end ? _i++ : _i--){ _results.push(_i); }
return _results;
}).apply(this).forEach(function(index) {
return content[index] = App.RowProxy.create({
index: index
});
});
},
objectAt: function(index) {
var content, row;
content = this.get('content');
row = content[index];
if (row && !row.get('error')) {
return row;
}
this.requestPage(Math.floor(index / 3 + 1));
return content[index];
}
});
App.ItemsController = Ember.Controller.extend({
hasHeader: false,
hasFooter: false,
rowHeight: 35,
numRows: 10,
store: null,
columns: Ember.computed(function() {
var columnNames, columns;
columnNames = ['Name','Desc','Category','Tags','Note'];
columns = columnNames.map(function(key, index) {
return Ember.Table.ColumnDefinition.create({
columnWidth: 150,
headerCellName: key.w(),
contentPath: key
});
});
return columns;
}).property(),
content: Ember.computed(function() {
return App.LazyDataSource.create({
content: new Array(this.get('numRows')),
store: this.get('store')
});
}).property('numRows')
});
While the requestPage method above is not strictly required now, it would be useful to use when I migrate to the RESTful API, I kept it.
The HTML template looks like this:
<script type="text/x-handlebars">
{{#link-to 'items'}}
<i class="icon-edit"></i>
Item Management
{{/link-to}}
<div class="page-content">
{{outlet}}
</div><!-- /.page-content -->
</script>
<script type="text/x-handlebars" data-template-name="items">
<div class="row">
{{table-component
columnsBinding="columns"
contentBinding="content"
}}
</div>
</script>
I wasn't too sure how to show the table but my attempt to define it via a View wasn't successful.
I'm using:
Ember 1.2.0
Handlebars 1.1.2
Ember-Data 1.0.0-beta.3
jQuery 2.0.3
Ember Table 0.0.2