Ember-table integration with Ember Data using FixtureAdapter - javascript

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

Related

Find duplicate object from one collection to another collection - using 2 arrays in knockout JS

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/

Kendo UI Angular Upload / Kendo Grid integration

Ok, here are the Versions:
Kendo UI v2014.3.1119
AngularJS v1.3.6
jQuery v#1.8.1 jquery.com
The issue is the following: I have a kendo upload that should populate a grid after a excel file is read. I'm using Kendo UI Angular Directives. Here are some key pieces of code:
Upload Html
<input name="files"
type="file"
kendo-upload
k-async="{ saveUrl: '{{dialogOptions.ImportUrl}}', autoUpload: false, batch: true }"
k-options="{localization: {uploadSelectedFiles: '{{messages.Global_Button_Import}}'}}"
k-error="onImportError"
k-select="onSelect"
k-success="onImportSuccess" k-multiple="false" />
Grid Html
<div kendo-grid="grid" k-options="gridOptions" k-ng-delay="gridOptions" k-rebind="gridOptions" >
</div>
Key pieces on the controller
angular.module('global').controller('ImportResultsController', [
'$scope', 'BaseApi', 'ImportResultsService', 'GridUtil', '$http', '$q', '$timeout',
function ($scope, BaseApi, ImportResultsService, GridUtil, $http, $q, $timeout) {
$scope.gridOptions;
$scope.gridColumns;
$scope.results = new kendo.data.ObservableArray([]);
//These columns should come from the server, right now are harcoded
$scope.getGridColumns = function () {
$scope.gridColumns = [
{ field: "Zone", width: 70, title: "Zone", template: "" },
{ field: "Aisle", width: 70, title: "Aisle", template: "" },
{ field: "Rack", width: 70, title: "Rack", template: "" },
{ field: "Shelf", width: 70, title: "Shelf", template: "" },
{ field: "Bin", width: 70, title: "Bin", template: "" },
//{ field: "DateEffectiveFrom", width: 70, title: "Date" },
{ field: "BinStatus", width: 70, title: "BinStatus", template: "" }
];
}
$scope.getClientGridOptions = function(columns, data, pageSize) {
var gridOptions = {
sortable: true,
dataSource: {
data: data,
pageSize: pageSize
},
selectable: 'row',
columns: columns,
pageable: {
pageSize: pageSize,
refresh: false,
pageSizes: [10, 20, 30],
messages: $.kendoMessages
},
};
return gridOptions
}
$scope.onImportSuccess = function (e) {
var files = e.files;
if (e.operation == "upload") {
console.log(files);
if (e.XMLHttpRequest.response != "") {
var model = $.parseJSON(e.XMLHttpRequest.response); //This step does not fail, model return is always filled
$scope.results = new kendo.data.ObservableArray([]);
for (var i = 0; i < model.Data.length; i++) {
$scope.results.push(model.Data[i]);
}
$scope.gridOptions = $scope.getClientGridOptions($scope.gridColumns, $scope.results, 10);
//$scope.grid.dataSource.data($scope.results); //This does not work
$scope.isDataReady = true;
// $("#grid").data("kendoGrid").dataSource.data($scope.results) //This does not work
// $scope.grid.refresh(); //This does not work
$scope.$apply()
}
}
}
}]);
The issues vary. Sometimes I get the data bound until the second uploaded file, and after the third time, I start receiving 'Cannot read property 'get' of undefined ' errors. When this second error happens, the bind works, but the error is present. Do you have any idea of what could it be?
In case of you need the url for the upload, here's the method. Is an MVC .net application. Since I always get the response correctly and it's a Json Array, I believe there's no issue there, but here's anyways.
dialogOptions.ImportUrl = LoadImportedBinLocations
MVC Controller
[System.Web.Http.HttpPost]
public ActionResult LoadImportedBinLocations(IEnumerable<HttpPostedFileBase> files)
{
bool success = false;
var importHistory = new PartsImportHistory();
List<dynamic> data = null;
try
{
//int divisor = 0;
//var y = 5 / divisor;
if (files != null)
{
using (var client = new ServiceLocator<IPartsService>())
{
foreach (var file in files)
{
string extension = Path.GetExtension(file.FileName);
bool isExcelFile = extension == ".xls" || extension == ".xlsx";
if (isExcelFile)
{
var filePath = UploadAttachment(file);
//importHistory = client.Service.SavePartsImportHistory(new PartsImportHistory
//{
// CreatedByName = CurrentContext.UserDisplayName,
// CreatedByUserID = CurrentContext.UserId,
// PartsImportStatus = (int)DMSModel.EnumStore.PartsImportStatus.InProgress,
// FilePath = filePath
//});
data = new List<dynamic>
{
new { Zone = "A", Aisle = "02", Rack = "06", Shelf = "20", Bin = "D", DateEffectiveFrom = DateTime.UtcNow, BinStatus = "Unblocked", IsValid= true, ImportError ="" },
new { Zone = "B", Aisle = "02", Rack = "06", Shelf = "10", Bin = "D", DateEffectiveFrom = DateTime.UtcNow, BinStatus = "Blocked", IsValid=false, ImportError="Zone does not Exist" }
};
success = true;
}
else
{
throw new Exception(WarpDMS.Globalization.Resources.PartsAdmin_ImportParts_ErrorFileFormat);
}
}
}
}
return Json(new { success = success, Data = data });
}
catch (Exception ex)
{
return Content(ex.Message ?? ex.ToString());
}
}
private string UploadAttachment(HttpPostedFileBase item)
{
string path = string.Empty;
string internalFileName = string.Empty;
string basePath = ConfigManager.ATTACHMENTS_PATH;
if (item != null && item.ContentLength > 0)
{
internalFileName = System.IO.Path.ChangeExtension(Guid.NewGuid().ToString(), System.IO.Path.GetExtension(item.FileName));
path = Path.Combine(basePath, internalFileName);
item.SaveAs(path);
}
return Path.Combine(basePath, internalFileName).Replace('\\', '/');
}

Windows Azure + DevExrpess (PhoneJs) getting ToDoList (Standart Sample)

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.

Emberjs dynamic segment: Error while loading route: TypeError {}

I'm trying to get familiar with dynamic segment here. Here is what I want to achieve:
When i access '/#/inventories', it will list the inventory model in the 'inventories' template. This is done successfully.
When i click on the individual inventory id, it will access /#/inventories/1 be 1 is the inventory id, and it will fire up the 'inventory' template. This is done successfully as well.
However when i try to access /#/inventories/1 directly from the address bar, when i press F5, it comes out this error - Error while loading route: TypeError {}
The full list of error:
Uncaught TypeError: Object function () {
if (!wasApplied) {
Class.proto(); // prepare prototype...
}
o_defineProperty(this, GUID_KEY, undefinedDescriptor);
o_defineProperty(this, '_super', undefinedDescriptor);
var m = meta(this);
m.proto = this;
if (initMixins) {
// capture locally so we can clear the closed over variable
var mixins = initMixins;
initMixins = null;
this.reopen.apply(this, mixins);
}
if (initProperties) {
// capture locally so we can clear the closed over variable
var props = initProperties;
initProperties = null;
var concatenatedProperties = this.concatenatedProperties;
for (var i = 0, l = props.length; i < l; i++) {
var properties = props[i];
Ember.assert("Ember.Object.create no longer supports mixing in other definitions, use createWithMixins instead.", !(properties instanceof Ember.Mixin));
for (var keyName in properties) {
if (!properties.hasOwnProperty(keyName)) { continue; }
var value = properties[keyName],
IS_BINDING = Ember.IS_BINDING;
if (IS_BINDING.test(keyName)) {
var bindings = m.bindings;
if (!bindings) {
bindings = m.bindings = {};
} else if (!m.hasOwnProperty('bindings')) {
bindings = m.bindings = o_create(m.bindings);
}
bindings[keyName] = value;
}
var desc = m.descs[keyName];
Ember.assert("Ember.Object.create no longer supports defining computed properties.", !(value instanceof Ember.ComputedProperty));
Ember.assert("Ember.Object.create no longer supports defining methods that call _super.", !(typeof value === 'function' && value.toString().indexOf('._super') !== -1));
if (concatenatedProperties && indexOf(concatenatedProperties, keyName) >= 0) {
var baseValue = this[keyName];
if (baseValue) {
if ('function' === typeof baseValue.concat) {
value = baseValue.concat(value);
} else {
value = Ember.makeArray(baseValue).concat(value);
}
} else {
value = Ember.makeArray(value);
}
}
if (desc) {
desc.set(this, keyName, value);
} else {
if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) {
this.setUnknownProperty(keyName, value);
} else if (MANDATORY_SETTER) {
Ember.defineProperty(this, keyName, null, value); // setup mandatory setter
} else {
this[keyName] = value;
}
}
}
}
}
finishPartial(this, m);
delete m.proto;
finishChains(this);
this.init.apply(this, arguments);
} has no method 'find'
Here is my app.js:
Gymi = Ember.Application.create();
// Route map
Gymi.Router.map(function() {
this.resource('inventories', { path: '/inventories' }, function() {
this.resource('inventory', { path: '/:inventory_id' });
});
this.resource('products');
});
// inventory models
Gymi.Inventory = Ember.Object.extend();
Gymi.Inventory.reopenClass({
items: [],
all: function() {
this.items = [{
id: 1,
name: 'item1',
cost: '20.00',
qty: 10
}, {
id: 2,
name: 'item2',
cost: '20.00',
qty: 10
}, {
id: 3,
name: 'item3',
cost: '20.00',
qty: 10
}, {
id: 4,
name: 'item4',
cost: '20.00',
qty: 10
}];
return this.items;
}
})
// inventory controller
Gymi.InventoriesController = Ember.Controller.extend({
inventories: Gymi.Inventory.all()
});
Here is the templates:
<script type="text/x-handlebars">
<h2>{{title}}</h2>
<ul>
<li>{{#linkTo 'inventories'}}Inventories{{/linkTo}}</li>
</ul>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="inventories">
<h2>Inventory</h2>
<table class="table">
<tbody>
{{#each inventory in inventories}}
{{#with inventory}}
<tr>
<td>{{#linkTo 'inventory' inventory}}{{id}}{{/linkTo}}</td>
<td>{{name}}</td>
<td>{{cost}}</td>
<td>{{qty}}</td>
</tr>
{{/with}}
{{/each}}
</tbody>
</table>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="inventory">
<h4>Inventory</h4>
<ul>
<li>{{id}}</li>
<li>{{name}}</li>
<li>{{cost}}</li>
<li>{{qty}}</li>
</ul>
</script>
Not an answer to the OP but to all those who are getting the error after Sept 1, 2013, it might be due to the update of Ember Data to the latest 1.0 version. So you have to use
this.store.find('model');
Instead of
App.Model.find();
Read more changes here.
That's an unhelpful error message, but the key part is at the end of it.
this.init.apply(this, arguments);
} has no method 'find'
When you visit the /inventories/1 route, ember will try to lookup the record for that id, using find, in the InventoryRoute's model hook. In this case on the Inventory. Since it can't find that method you get this error.
Adding an Inventory.find method that returns the record matching params.inventory_id will fix this issue.
This error appears if your route is missing the parameter of the model method.
The following code works when visiting /inventory/1 from a link-to but not opening the page from the URL:
App.InventoryRoute = Ember.Route.extend({
model: function() {
this.store.find('inventory', params.inventory_id)
}
});
Adding the missing params fixes. This code works both from a link-to and directly from the URL:
App.InventoryRoute = Ember.Route.extend({
model: function(params) {
this.store.find('inventory', params.inventory_id)
}
});
For ember-data < 0.14 this is the code
App.InventoryRoute = Ember.Route.extend({
model: function(params) {
App.Inventory.find(params.inventory_id)
}
});

How to preselect items within a Fuel UX treeview?

so I've implemented the treeview of Fuel UX within my website. Whenever it's loaded, I need to reselect the items I want manually. Is there a possibility to preselect certain items after each reload?
Thanks in advance!
I was in the same situation since yesterday and could now solve the problem with the solution below. Just explaining that I used the methods present on the button "select nested Test Item 1" on this page. Here's the solution:
var preSelectFolder = function ($treeEl, folder, $parentEl) {
var $elParent = $parentEl || $treeEl;
if (folder.type == "folder") {
var $folderEl = $elParent.find("div.tree-folder-name").filter(function (_, treeFolder) {
return $(treeFolder).text() == folder.name;
}).parent();
$treeEl.one("loaded", function () {
$.each(folder.children, function (i, item) {
preSelectFolder($treeEl, item, $folderEl.parent());
});
});
$treeEl.tree("selectFolder", $folderEl);
}
else {
preSelectItem($treeEl, folder, $elParent);
}
};
var preSelectItem = function ($treeEl, item, $parentEl) {
var $elParent = $parentEl || $treeEl;
if (item.type == "item") {
var $itemEl = $elParent.find("div.tree-item-name").filter(function (_, treeItem) {
return $(treeItem).text() == item.name && !$(treeItem).parent().is(".tree-selected");
}).parent();
var itemId = $($itemEl).data() != null ? $($itemEl).data().id : "";
if (itemId == item.id)
$treeEl.tree("selectItem", $itemEl);
}
else if (item.type == "folder") {
preSelectFolder($treeEl, item, $elParent);
}
};
And in the event of 'loaded' I use this code:
element.on('loaded', function (e) {
angular.forEach(scope.items, function (item) {
preSelectItem($("#BuildTree"), item);
});
});
I use AngularJs so just replace "angular.forEach" for each function of Jquery and "scope.items" are items that should be pre-selected. In my case the items are in the following format:
[
{ name: 'Dir 1', type: 'folder', id: 'D1' },
{ name: 'Dir 2', type: 'folder', id: 'D2' },
{ name: 'Item 1', type: 'item', id: 'i1' },
{ name: 'Item 2', type: 'item', id: 'i2' }
]
Hope that helps.
If by manually, you mean you're actually clicking on the items again there should be a way to do this more programmatically.
I haven't tested it, but if you call $('#MyTree').tree('selectItem', $el) where $el is a .tree-item element, that should select the item.
It would be nice for your datasource to be able to tell the tree which items are selected. I see you've posted the feature request to https://fuelux.uservoice.com/forums/181290-general/suggestions/4097231-add-preselect-option-for-treeview which is great - anyone else reading this who agrees it would be useful should vote there.
I make if for ASP.NET MVC. I use a dynamic tree.
At first I received a route for selected item
[{
"id": 1, // parent category
"name": "Все категории",
}, {
"id": 56, // 1-st sub category
"name": "Для дома",
}, {
"id": 63, // item
"name": "Домашние растения",
}]
Then it need to switch off Async request for Ajax in dataSource function: 'async':false
This is all code:
#{
var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string catRoute = jsonSerializer.Serialize(ViewBag.catRoute);
}
var catRoute = $.parseJSON('#Html.Raw(catRoute)'); // this is object of item route
function dynamicDataSource(openedParentData, callback) {
var childNodesArray = [];
$.ajax({
'type': 'post',
'url': '#Url.Action("getFuelUxTree", "Category", new { area = "Root" })',
'data': openedParentData,
'async':false // switch off ajax request
})
.done(function (data) {
childNodesArray = data;
lastTree = data;
callback({
data: childNodesArray
});
});
}
$('#categoryTree').tree({
dataSource: dynamicDataSource,
multiSelect: false,
folderSelect: false
});
// iterate all route items and open category
for (var i = 0; i < catRoute.length; i++) {
$('li#'+catRoute[i].id+' button', '#categoryTree').click();
}

Categories