I am currently trying to learn KnockOutJS. I thought it would be a great idea to create a simple task-list application.
I do not want to write a long text here, let's dive into my problem. I appreciate all kind of help - I am new to KnockOutJS tho!
The tasks are declared as followed:
var Task = function (data) {
var self = this;
self.name = ko.observable(data.name);
self.status = ko.observable(data.status);
self.priority = ko.observable(data.priority);
}
And the view model looks like this
var TaskListViewModel = function() {
var self = this;
self.currentTask = ko.observable();
self.currentTask(new Task({ name: "", status: false, priority: new Priority({ name: "", value: 0 }) }));
self.tasksArr = ko.observableArray();
self.tasks = ko.computed(function () {
return self.tasksArr.slice().sort(self.sortTasks);
}, self);
self.sortTasks = function (l, r) {
if (l.status() != r.status()) {
if (l.status()) return 1;
else return -1;
}
return (l.priority().value > r.priority().value) ? 1 : -1;
};
self.priorities = [
new Priority({ name: "Low", value: 3 }),
new Priority({ name: "Medium", value: 2 }),
new Priority({ name: "High", value: 1 })
];
// Adds a task to the list
// also saves updated task list to localstorage
self.addTask = function () {
self.tasksArr.push(new Task({ name: self.currentTask().name(), status: false, priority: self.currentTask().priority() }));
self.localStorageSave();
self.currentTask().name("");
};
// Removes a task to a list
// also saves updated task list to localstorage
self.removeTask = function (task) {
self.tasksArr.remove(task);
self.localStorageSave();
};
// Simple test function to check if event is fired.
self.testFunction = function (task) {
console.log("Test function called");
};
// Saves all tasks to localStorage
self.localStorageSave = function () {
localStorage.setItem("romaTasks", ko.toJSON(self.tasksArr));
};
// loads saved data from localstorage and parses them correctly.
self.localStorageLoad = function () {
var parsed = JSON.parse(localStorage.getItem("romaTasks"));
if (parsed != null) {
var tTask = null;
for (var i = 0; i < parsed.length; i++) {
tTask = new Task({
name: parsed[i].name,
status: parsed[i].status,
priority: new Priority({
name: parsed[i].priority.name,
value: parsed[i].priority.value
})
});
self.tasksArr.push(tTask);
}
}
};
self.localStorageLoad();
}
What I want to do in my html is pretty simple.
All tasks I have added are saved to localStorage. The save function is, as you can see, called each time an element has been added & removed. But I also want to save as soon as the status of each task has been changed, but it is not possible to use subscribe here, such as
self.status.subscribe(function() {});
because I cannot access self.tasksArr from the Task class.
Any idea? Is it possible to make the self.tasksArr public somehow?
Thanks in advance!
Try this:
self.addTask = function () {
var myTask = new Task({ name: self.currentTask().name(), status: false, priority: self.currentTask().priority() })
myTask.status.subscribe(function (newValue) {
self.localStorageSave();
});
self.tasksArr.push(myTask);
self.localStorageSave();
self.currentTask().name("");
};
Related
I m new in suitescripts. I have made a Suitelet Form script with 3 fields which will act as filters on the scheduled script. The scheduled script in sending the PDF file to a certain email after filtering the 3 values of suit let script from my saved search.
When I hit the button on suitelet form, after entering the fields, the scheduled script goes on processing for 1 hour and then gets failed.
I think I have placed the wrong filters in the loading of My saved search in my scheduled script.
The saved search (customsearch_mx_itemsearch) is without any filters or criteria.
Please help if anyone knows. Thank you
My Suitelet form Script:
define(['N/ui/serverWidget', 'N/search', 'N/render', 'N/runtime', 'N/file', 'N/task'],
function (ui, search, render, runtime, file, task) {
/**
* main function for suitelet
* #param {object} ctx
*/
function onRequest(ctx) {
var req = ctx.request;
var res = ctx.response;
var param = req.parameters;
/**
* create form is creating the UI for report generation
*/
if (req.method === 'GET') {
// createForm(req, res, param);
createForm(req, res, param);
} else {
generateReport(req, res, param);
}
}
// R E Q U E S T
function createForm(req, res, param) {
if (req.method === 'GET') {
var form = ui.createForm({
title: 'Generate Item Report'
});
var item = form.addField({
id: 'custpage_selectitem',
type: ui.FieldType.SELECT,
label: 'Select Item',
source: 'item'
});
item.isMandatory = true;
var gender = form.addField({
id: 'custpage_selectgender',
type: ui.FieldType.SELECT,
label: 'Select Gender',
source: 'customrecord6'
});
gender.isMandatory = true;
var fromDate = form.addField({
id: 'custpage_selectdate',
// type: ui.FieldType.DATETIME,
type: ui.FieldType.DATE,
label: 'Select Date/Time',
});
form.addSubmitButton({
label: 'Generate Report'
});
res.writePage(form);
}
}
// R E S P O N C E
function generateReport(req, res, param) {
var param = req.parameters;
log.debug('parameters', param);
var script = runtime.getCurrentScript();
var filters = {
'isgender': param.custpage_selectgender,
'isItem': param.custpage_selectitem,
'fromDate': param.custpage_selectdate
};
log.debug('filters', filters);
var scriptTask = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT });
// scriptTask.scriptId = 3920;
scriptTask.scriptId = 'customscript_mx_itemreport_ss';
scriptTask.deploymentId = 'customdeploy_mx_itemreport_ss';
scriptTask.params = {
custscript_searchfilter_report: JSON.stringify(filters)
};
log.debug('workingtillhere');
var scriptTaskId = scriptTask.submit();
res.write("Your report is being generated. It will be emailed to you shortly.")
}
return {
onRequest: onRequest
};
});
My Scheduled script:
define(['N/ui/serverWidget', 'N/search', 'N/render', 'N/runtime', 'N/file', 'N/email'],
function (ui, search, render, runtime, file, email) {
function execute() {
try {
generateReport();
}
catch (e) {
log.error('generateReport ERROR', e);
}
}
function generateReport(req, res, param) {
var slfilters = runtime.getCurrentScript().getParameter({ name: 'custscript_searchfilter_report' });
log.debug('slfilters', slfilters);
if (!!slfilters) {
slfilters = JSON.parse(slfilters);
}
log.debug('slfilters2', slfilters);
var getUser = runtime.getCurrentUser();
var gender = slfilters.isgender
log.debug('gender', gender)
var item = slfilters.isItem
log.debug('item', item)
var item = getItems(item, gender);
log.debug('items table', item)
var xmlTemplateFile = file.load(3918);
var template = script.getParameter({ name: 'custscript_template' });
var renderer = render.create();
renderer.templateContent = xmlTemplateFile.getContents();
var customSources = {
alias: 'searchdata',
format: render.DataSource.JSON,
data: JSON.stringify({
value: item,
})
};
renderer.addCustomDataSource(customSources);
var xml = renderer.renderAsString();
var pdf = render.xmlToPdf({
"xmlString": xml
});
email.send({
author: 317,
recipients: 'aniswtf#gmail.com',
subject: 'Item Report',
body: 'Report Generated: ',
attachments: [pdf]
});
}
//
// ─── GET RESULTS ───────────────────────────────────────────────────
//
const getResults = function (set) {
var results = [];
var i = 0;
while (true) {
var result = set.getRange({
"start": i,
"end": i + 1000
});
if (!result) break;
results = results.concat(result);
if (result.length < 1000) break;
i += 1000;
}
return results;
};
//
// ─── GET ITEMS ───────────────────────────────────────────────────
//
function getItems(item, gender) {
try {
var itemSearch = search.load({
id: 'customsearch_mx_itemsearch'
});
var defaultFilters = itemSearch.filters;
var arrFilters = [];
arrFilters.push(search.createFilter({
name: 'custitem5',//gender
operator: 'anyof',
values: [gender]
}));
arrFilters.push(search.createFilter({
name: 'internalid',
operator: 'anyof',
values: [item]
}));
//defaultFilters.push(arrFilters)
defaultFilters = defaultFilters.concat(arrFilters);
var results = getResults(itemSearch.run()).map(function (x) {
return {
'category': x.getText({
name: "custitem10",
join: "parent"
}),
'season': x.getValue({
name: "custitem11",
join: "parent"
}),
'riselabel': x.getValue({
name: "custitem_itemriselabel",
join: "parent"
}),
'fit': x.getValue({
name: "custitem9",
join: "parent"
}),
'name': x.getValue({ //sku
name: "itemid",
join: "parent"
}),
'style': x.getValue({
name: "custitem8",
join: "parent"
}),
'inseam': x.getValue({
name: "custitem7",
join: "parent"
}),
'wash': x.getValue({
name: "custitem_washname",
join: "parent"
}),
};
});
return results;
} catch (e) {
log.error('error in getItems', e)
}
}
return {
execute: execute
};
});
You have the req, res, and param arguments defined for generateReport(), but you aren't actually populating them when you call generateReport() within execute(). You will need to pass values for those parameters.
I have problems with object scope.
Here is my class code
// Table list module
function DynamicItemList(data, settings, fields) {
if (!(this instanceof DynamicItemList)) {
return new DynamicItemList(data, settings, fields);
}
this.data = data;
this.settings = settings;
this.fields = fields;
this.dataSet = {
"Result": "OK",
"Records": this.data ? JSON.parse(this.data) : []
};
this.items = this.dataSet["Records"];
this.generateId = makeIdCounter(findMaxInArray(this.dataSet["Records"], "id") + 1);
this.dataHiddenInput = $(this.settings["hidden-input"]);
}
DynamicItemList.RESULT_OK = {"Result": "OK"};
DynamicItemList.RESULT_ERROR = {"Result": "Error", "Message": "Error occurred"};
DynamicItemList.prototype = (function () {
var _self = this;
var fetchItemsList = function (postData, jtParams) {
return _self.dataSet;
};
var createItem = function (item) {
item = parseQueryString(item);
item.id = this.generateId();
_self.items.push(item);
return {
"Result": "OK",
"Record": item
}
};
var removeItem = function (postData) {
_self.items = removeFromArrayByPropertyValue(_self.items, "id", postData.id);
_self.dataSet["Records"] = _self.items;
_self.generateId = makeIdCounter(findMaxInArray(_self.dataSet["Records"], "id") + 1);
return DynamicItemList.RESULT_OK;
};
return {
setupTable: function () {
$(_self.settings["table-container"]).jtable({
title: _self.settings['title'],
actions: {
listAction: fetchItemsList,
deleteAction: removeItem
},
fields: _self.fields
});
},
load: function () {
$(_self.settings['table-container']).jtable('load');
},
submit: function () {
_self.dataHiddenInput.val(JSON.stringify(_self.dataSet["Records"]));
}
};
})();
I have problems with accessing object fields.
I tried to use self to maintain calling scope. But because it is initialized firstly from global scope, I get Window object saved in _self.
Without _self just with this it also doesn't work . Because as I can guess my functions fetchItemsList are called from the jTable context and than this points to Window object, so I get error undefined.
I have tried different ways, but none of them work.
Please suggest how can I solve this problem.
Thx.
UPDATE
Here is version with all method being exposed as public.
// Table list module
function DynamicItemList(data, settings, fields) {
if (!(this instanceof DynamicItemList)) {
return new DynamicItemList(data, settings, fields);
}
this.data = data;
this.settings = settings;
this.fields = fields;
this.dataSet = {
"Result": "OK",
"Records": this.data ? JSON.parse(this.data) : []
};
this.items = this.dataSet["Records"];
this.generateId = makeIdCounter(findMaxInArray(this.dataSet["Records"], "id") + 1);
this.dataHiddenInput = $(this.settings["hidden-input"]);
}
DynamicItemList.RESULT_OK = {"Result": "OK"};
DynamicItemList.RESULT_ERROR = {"Result": "Error", "Message": "Error occurred"};
DynamicItemList.prototype.fetchItemsList = function (postData, jtParams) {
return this.dataSet;
};
DynamicItemList.prototype.createItem = function (item) {
item = parseQueryString(item);
item.id = this.generateId();
this.items.push(item);
return {
"Result": "OK",
"Record": item
}
};
DynamicItemList.prototype.setupTable = function () {
$(this.settings["table-container"]).jtable({
title: this.settings['title'],
actions: this,
fields: this.fields
});
};
DynamicItemList.prototype.load = function () {
$(this.settings['table-container']).jtable('load');
};
DynamicItemList.prototype.submit = function () {
this.dataHiddenInput.val(JSON.stringify(this.dataSet["Records"]));
};
DynamicItemList.prototype.removeItem = function (postData) {
this.items = removeFromArrayByPropertyValue(this.items, "id", postData.id);
this.dataSet["Records"] = this.items;
this.generateId = makeIdCounter(findMaxInArray(this.dataSet["Records"], "id") + 1);
return DynamicItemList.RESULT_OK;
};
DynamicItemList.prototype.updateItem = function (postData) {
postData = parseQueryString(postData);
var indexObjToUpdate = findIndexOfObjByPropertyValue(this.items, "id", postData.id);
if (indexObjToUpdate >= 0) {
this.items[indexObjToUpdate] = postData;
return DynamicItemList.RESULT_OK;
}
else {
return DynamicItemList.RESULT_ERROR;
}
};
Your assigning a function directly to the prototype. DynamicItemList.prototype= Normally it's the form DynamicItemList.prototype.somefunc=
Thanks everyone for help, I've just figured out where is the problem.
As for last version with methods exposed as public.
Problematic part is
$(this.settings["table-container"]).jtable({
title: this.settings['title'],
actions: {
listAction: this.fetchItemsList,
createAction: this.createItem,
updateAction: this.updateItem,
deleteAction: this.removeItem
},
fields: this.fields
});
};
Here new object is created which has no idea about variable of object where it is being created.
I've I changed my code to the following as you can see above.
$(this.settings["table-container"]).jtable({
title: this.settings['title'],
actions: this,
fields: this.fields
});
And now it works like a charm. If this method has drawbacks, please let me know.
My problem was initially in this part and keeping methods private doesn't make any sense because my object is used by another library.
Thx everyone.
You need to make your prototype methods use the this keyword (so that they dyynamically receive the instance they were called upon), but you need to bind the instance in the callbacks that you pass into jtable.
DynamicItemList.prototype.setupTable = function () {
var self = this;
function fetchItemsList(postData, jtParams) {
return self.dataSet;
}
function createItem(item) {
item = parseQueryString(item);
item.id = self.generateId();
self.items.push(item);
return {
"Result": "OK",
"Record": item
};
}
… // other callbacks
$(this.settings["table-container"]).jtable({
title: this.settings['title'],
actions: {
listAction: fetchItemsList,
createAction: createItem,
updateAction: updateItem,
deleteAction: removeItem
},
fields: this.fields
});
};
I'm trying to populate a drop down box rendered by Mithril's view from methods being called outside of its module (not sure if this terminology is correct, but outside of the property which contains the view, model and controller).
This Chrome extension adds a new field to an existing page and depending on what the user select, the drop down box should refresh to items pertaining to the selected item. I can get up to the stage of getting the new list of items, but i cannot get the drop down list to redraw with the new objects.
The following shows the module which gets inserted inside an existing page:
var ItemsList = {
model: function () {
this.list = function (id) {
var d = m.deferred()
// Calls Chrome extension bg page for retrieval of items.
chromeExt.getItems(pId, function (items) {
// Set default values initially when the controller is called.
if (items.length === 0) {
items = [
{name: 'None', value: 'none'}
]
}
d.resolve(items || [])
})
return d.promise
}
},
controller: function () {
this.model = new ItemsList.model()
this.index = m.prop(0)
this.onchange = function (e) {
console.info('ctrl:onchange', e.target)
}
// Initialise the drop down list array list.
this.dropDownItemsList = m.prop([]);
// This sets the default value of the drop down list to nothing by calling the function in the model,
// until the user selects an item which should populate the drop down list with some values.
this.getItems = function(pId) {
this.model.list(pId).then(function (data) {
this.dropDownItemsList(data)
m.redraw()
}.bind(this))
}
this.getItems(0);
},
view: function (ctrl) {
var SELECT_ID = 'record_select'
return vm.Type() ? m('div', [
m('.form__item', [
m('.label', [
m('label', {
htmlFor: SELECT_ID
}, 'ID')
]),
m('.field', [
m('select#' + SELECT_ID, {
onchange: ctrl.onchange.bind(ctrl)
},
ctrl.dropDownItemsList().map(function (it, i) {
return m('option', {
value: it.value,
checked: ctrl.model.index === i
}, it.name)
})
),
])
]),
]) : null
}
}
And it is mounted using
m.mount("element name here", ItemsList);
The code which checks to see if the item has changed is using a mutation observer, and whenever it detects changes to a certain field, it will call a method to get the new values. I can see that the return value has my new items.
I have tried various different methods on trying to update the drop down list, first by trying to set the "this.list" with the new items list i've got, or trying to create a returnable method on the controller which i can call when the mutation observer fires.
After getting the new items, how can i make the drop down list show the new items which has been retrieved?
I have read guides which shows functions in the controller or model being run - but only if they've been defined to use them already in the view (i.e. have an onclick method on the view which calls the method) but so far i cannot figure out how to update or call methods from outside of the module.
Is there a way to achieve the above or a different method i should approach this?
After some more research into how Mithril works, seems like that it's not possible to call any functions defined within the component.
Due to this, i have moved the model outside of the component (so now it only has the controller and the view defined) and bound the view to use the model outside of the component.
Now calling a function which updates the model (which is now accessible from elsewhere in the code) and redrawing shows the correct values that i need.
If I understand correctly, you need to have two variables to store your lists, one to store the old list and one to store the updated list so you can always map the updated one and go to your old one if you need.
Here is a simple implementation of a drop down list with some methods to update and search. You can update the list on the fly using the methods.
mithDropDown
jsFiddle
var MythDropDown = function(list) {
if (Array.isArray(list))
this.list = list;
else
list = [];
if (!(this instanceof MythDropDown))
return new MythDropDown(list);
var self = this;
this.selected = {
name: list[0],
index: 0
};
this.list = list;
};
MythDropDown.prototype.view = function(ctrl) {
var self = this;
return m('select', {
config: function(selectElement, isinit) {
if (isinit)
return;
self.selectElement = selectElement;
self.update(self.list);
},
onchange: function(e) {
self.selected.name = e.target.value;
self.selected.index = e.target.selectedIndex;
}
},
this.list.map(function(name, i) {
return m('option', name);
}));
};
MythDropDown.prototype.getSelected = function() {
return (this.selected);
};
MythDropDown.prototype.update = function(newList) {
this.list = newList;
this.selectElement.selectedIndex = 0;
this.selected.name = newList[0];
this.selected.index = 0;
};
MythDropDown.prototype.sort = function() {
this.list.sort();
this.update(this.list);
};
MythDropDown.prototype.delete = function() {
this.list.splice(this.selected.index, 1);
this.update(this.list);
};
var list = ['test option 1', 'test option 2'];
var myList = new MythDropDown(list);
var main = {
view: function() {
return m('.content',
m('button', {
onclick: function() {
var L1 = ['Banana', 'Apple', 'Orange', 'Kiwi'];
myList.update(L1);
}
},
'Fruits'),
m('button', {
onclick: function() {
var L1 = ['Yellow', 'Black', 'Orange', 'Brown', 'Red'];
myList.update(L1);
}
},
'Colors'),
m('button', {
onclick: function() {
myList.sort();
}
},
'Sort'),
m('button', {
onclick: function() {
myList.delete();
}
},
'Remove Selected'),
m('', m.component(myList),
m('', 'Selected Item: ' + myList.selected.name, 'Selected Index: ' + myList.selected.index)
)
);
}
};
m.mount(document.body, main);
<script src="https://cdnjs.cloudflare.com/ajax/libs/mithril/0.2.3/mithril.min.js"></script>
So I'm trying to load JSON from a server via AJAX call. I'm able to map it fine into an array that is being binded in HTML. These objects are saved into an array that is being used as the value for a select tag. If I output to the console what's in the array, all the objects show up fine. But these objects don't show as if they have been preselected in the select box.
What I'm trying to do is have the previous data that a user saved from an old session and continue where they left off without having to redo everything again. So I'm loading all old data and putting it back where it used to be by preselecting the option for them.
Here is the JS I currently have:
function BracketsViewModel() {
self.AfcTeams = ko.observableArray([]);
// Normally pulled from server via AJAX with more teams. Hardcoded for simplicity
self.AfcTeams.push(new TeamModel({
Tricode: "CIN",
DisplayName: "Bengals"
}));
self.AfcTeams.push(new TeamModel({
Tricode: "BUF",
DisplayName: "Bills"
}));
self.AfcTeams.push(new TeamModel({
Tricode: "DEN",
DisplayName: "Broncos"
}));
self.AfcTeams.push(new TeamModel({
Tricode: "CLE",
DisplayName: "Browns"
}));
self.AfcTeams.push(new TeamModel({
Tricode: "SD",
DisplayName: "Chargers"
}));
// Temporary array that holds Team object
self.AfcSelectedWildCards = [];
for (var i = 0; i <= 5; i++) {
self.AfcSelectedWildCards.push(ko.observable());
}
// Holds selected teams that go to next round
self.AfcDivisionals = ko.computed(function () {
var tmp = [];
ko.utils.arrayForEach(self.AfcSelectedWildCards, function (team) {
if (team()) {
tmp.push(team());
}
});
return tmp;
});
// Other properties not shown for simplicity
// This will be loaded from server via AJAX call
var bracketsObject = {
AfcTeams: [{
Tri: "CIN",
Name: "Bengals",
Rank: "1"
}, {
Tri: "HOU",
Name: "Texans",
Rank: "2"
}, {
Tri: "NE",
Name: "Patriots",
Rank: "3"
}, {
Tri: "NYJ",
Name: "Jets",
Rank: "5"
}, {
Tri: "DEN",
Name: "Broncos",
Rank: "4"
}, {
Tri: "KC",
Name: "Chiefs",
Rank: "6"
}]
};
var afcteams = $.map(bracketsObject.AfcTeams, function (team) {
return new AltTeamModel(team);
});
// Saving objects to array that is being binded in HTML
for (var i = 0; i <= 5; i++) {
self.AfcSelectedWildCards[i] = ko.observable(afcteams[i]);
}
}
function TeamModel(data) {
if (data) {
this.Tri = data.Tricode;
this.Name = data.DisplayName;
} else {
this.Tri = "";
this.Name = "";
}
this.Rank = ko.observable(0);
}
function AltTeamModel(data) {
this.Tri = data.Tri;
this.Name = data.Name;
this.Rank = ko.observable(data.Rank);
}
ko.applyBindings(new BracketsViewModel());
Here is the Fiddle
I appreciate any help I can get.
The first issue is that you are referencing self, but never declaring it. You need to add var self = this; at the top of BracketsViewModel.
The next problem is that AfcTeams is an observable array of TeamModels, but AfcSelectedWildCards is an array of AltTeamModel. They need to be the same view model for options and value to match up.
One way around this is to set optionsValue and value both to 'Tri' as follows:
<select class="form-control"
data-bind="options: AfcTeams,
optionsText: 'Name',
optionsCaption: '-- Team --',
optionsValue: 'Tri',
value: AfcSelectedWildCards[0]().Tri"></select>
Here is a fiddle with these two fixes: http://jsfiddle.net/qpolarbear/8kkamzy7/
Only the Bengals and Broncos are selected because they are the only matching teams between AfcTeams and AfcSelectedWildCards.
So after taking a break from this project, I finally figured out how to bind the objects loaded via AJAX. The problem was that Knockout was binding the document before the AJAX calls were finished so, for whatever reason, the binding wasn't reflecting these changes. What I decided to do was time out the document from applying the binding and load everything from the server first. I then passed in all the objects into the View Model and apply the binding on a half second delay. Everything works great now. Here is the code:
function TeamModel(data, isPreData) {
if (isPreData) {
this.Tri = data.Tri;
this.Name = data.Name;
this.Rank = ko.observable(data.Rank);
} else {
if (data) {
this.Tri = data.Tricode;
this.Name = data.DisplayName;
} else {
this.Tri = "";
this.Name = "";
}
this.Rank = ko.observable(0);
}
}
var afcteams;
$.getJSON('/Brackets/GetBrackets', { id: someId}, function (bracketsObject) {
if (bracketsObject) {
afcteams = $.map(bracketsObject.AfcTeams, function (team) {
return new TeamModel(team, true);
});
}
}).fail(function () {
alert("There was an error getting data from the server.");
});
var teams;
$.getJSON('/Brackets/GetAFCTeams', function (data) {
teams = $.map(data, function (team) {
return new TeamModel(team, false);
});
});
function SetBindings(afcteams, teams) {
ko.applyBindings(new BracketsViewModel(afcteams, teams));
}
setTimeout(function() {
SetBindings(afcteams, teams);
}, 500);
I am trying to build datagrid with sorting, searching and paging enabled. Therefore, I am using fuelux-datagrid.
MY backbone view looks like this:
var app = app || {};
$(function ($) {
'use strict';
// The Players view
// ---------------
app.PlayersView = Backbone.View.extend({
template: _.template( $("#player-template").html() ),
initialize: function () {
if(this.collection){
this.collection.fetch();
}
this.listenTo(this.collection, 'all', this.render);
},
render: function () {
this.$el.html( this.template );
var dataSource = new StaticDataSource({
columns: [
{
property: 'playername',
label: 'Name',
sortable: true
},
{
property: 'age',
label: 'A',
sortable: true
}
],
data: this.collection.toJSON(),
delay: 250
});
$('#MyGrid').datagrid({
dataSource: dataSource,
stretchHeight: true
});
}
});
});
The player template just contain the template as given in fuelux datagrid . My routing code somewhere instantiate app.playerview with collection as
new app.PlayersView({
collection : new app.PlayersCollection
}));
My players collection contains list of player model as below
[{
"id":1,
"playername":"rahu",
"age":13
},
{
"id":2,
"playername":"sahul",
"age":18
},
{
"id":3,
"playername":"ahul",
"age":19
}]
My datasource class/function to construct datasoruce with columns and data method is as given in datasource constructor
However, I get the error the " datasource in not defined ". Can anybody help me?
I just wanted to hack the code so that instead of datasource constructed from local data.js in given example, I want to construct the datasource so that it takes data from playercollection.
Also, how to add the one extra column so that we can put edit tag insdie and its should be able to edit the particular row model on clicking that edit.
I have been stucking around these a lot. It would be great help to figure out the answer.
I was stucking around datasource.
I modified the datasource as follows and then it worked.
var StaticDataSource = function (options) {
this._formatter = options.formatter;
this._columns = options.columns;
this._delay = options.delay || 0;
this._data = options.data;
};
StaticDataSource.prototype = {
columns: function () {
return this._columns;
},
data: function (options, callback) {
var self = this;
setTimeout(function () {
var data = $.extend(true, [], self._data);
// SEARCHING
if (options.search) {
data = _.filter(data, function (item) {
var match = false;
_.each(item, function (prop) {
if (_.isString(prop) || _.isFinite(prop)) {
if (prop.toString().toLowerCase().indexOf(options.search.toLowerCase()) !== -1) match = true;
}
});
return match;
});
}
// FILTERING
if (options.filter) {
data = _.filter(data, function (item) {
switch(options.filter.value) {
case 'lt5m':
if(item.population < 5000000) return true;
break;
case 'gte5m':
if(item.population >= 5000000) return true;
break;
default:
return true;
break;
}
});
}
var count = data.length;
// SORTING
if (options.sortProperty) {
data = _.sortBy(data, options.sortProperty);
if (options.sortDirection === 'desc') data.reverse();
}
// PAGING
var startIndex = options.pageIndex * options.pageSize;
var endIndex = startIndex + options.pageSize;
var end = (endIndex > count) ? count : endIndex;
var pages = Math.ceil(count / options.pageSize);
var page = options.pageIndex + 1;
var start = startIndex + 1;
data = data.slice(startIndex, endIndex);
if (self._formatter) self._formatter(data);
callback({ data: data, start: start, end: end, count: count, pages: pages, page: page });
}, this._delay)
}
};
Infact, I just removed following code and its associated braces.
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['underscore'], factory);
} else {
root.StaticDataSource = factory();
}
}(this, function () {
I dont know what exactly the above code is doing an what dependdencies they have over.