I am new to backbone.js
I am adding rows dynamical in table(HTML), but when I print table data on save button it display empty data, my code is as follows
(function($){
Backbone.sync = function(method, model, success, error){
success();
}
var Person = Backbone.Model.extend({
defaults: {
srNo:1,
name: ''
}
});
var ListPerson = Backbone.Collection.extend({
model: Person
});
var ItemView = Backbone.View.extend({
tagName: 'tr', // name of tag to be created
events: {
'click span#spanDelete': 'remove'
},
initialize: function(){
_.bindAll(this, 'render', 'unrender', 'remove');
this.model.bind('add', this.render);
this.model.bind('remove', this.unrender);
},
render: function(){
$(this.el).append("<td>"+this.model.get('srNo')+"</td><td><input type='text' id='txt1' value="+this.model.get('name')+"></td><td><span class='delete' id='spanDelete' style='cursor:pointer; color:red; font-family:sans-serif;'>[delete]</span></td>");
return this;
},
unrender: function(){
$(this.el).remove();
},
remove: function(){
this.model.destroy();
}
});
var ListView = Backbone.View.extend({
el: $('body'), // attaches `this.el` to an existing element.
initialize: function(){
_.bindAll(this, 'render', 'addItem', 'appendItem');
this.collection = new ListPerson();
this.collection.bind('add', this.appendItem);
this.counter = 0;
this.render();
},
events: {
'click button#btnAdd': 'addItem',
'click button#btnSave': 'saveData'
},
render: function(){
var self = this;
$(this.el).append("<button id='btnAdd'>Add list item</button>");
$(this.el).append("<table border=1 id='dtl1'></table>");
$(this.el).append("<button id='btnSave'>Save</button>");
_(this.collection.models).each(function(person){
self.appendItem(person);
}, this);
},
addItem: function(){
this.counter++;
var person = new Person();
person.set({
srNo: this.counter // modify item defaults
});
this.collection.add(person);
},
appendItem: function(item){
var itemView = new ItemView({
model: item
});
$('table', this.el).append(itemView.render().el);
},
saveData: function(){
var obj=this.collection.toJSON();
var str_json = JSON.stringify(obj);
alert(str_json);
}
});
var listView = new ListView();
})(jQuery);
Name is not display in output
From what you have posted, I do not see you setting name attribute of your Person model anywhere. Within your addItem method, I see you setting the srNo attribute but nothing is done to the name as far as I can see here.
Relevant part of your code below,
var person = new Person();
person.set({
srNo: this.counter // modify item defaults
});
So you need set your name attribute like you are setting the srNo attribute
I got one tricky solution for this, i trap change event of inputtext in event block of ItemView(In above example) as events: {'click span#spanDelete': 'remove','change input#name':'textChange' }, and in textChange method i write following code textChange: function(e){
this.model.set('name',$(e.currentTarget).val());
}When i print collection value in alert i got all names inserted in inputtext.
Related
I am using Shield UI for my Java application.
I created a custom insert window with "command" as follows:
toolbar: [
{
buttons: [
//{ commandName: "insert", caption: "Agregar Solicitud" }
{ cls: "insertButton", caption: "Agregar Solicitud", click: insertRecord }
],
position: "top"
},
Code for insertRecord:
function insertRecord(index) {
//alert(JSON.stringify(index));
index = 0;
var grid = $("#grid").swidget(),
item = grid.dataItem(index);
initializeWindowWidgets();
editedRowIndex = index;
$("#solId").swidget().value(item.solId);
$("#atmid").swidget().value(item.atmid);
$("#fechaAbastecimiento").swidget().value(item.fechaAbastecimiento);
$("#cargar").swidget().checked(item.cargar);
$("#emergencia").swidget().checked(item.emergencia);
$("#solId").swidget().enabled(true);
$("#atmid").swidget().enabled(true);
$("#fechaAbastecimiento").swidget().enabled(true);
$("#cargar").swidget().enabled(true);
$("#emergencia").swidget().enabled(true);
$("#save").swidget().enabled(true);
$("#window").swidget().visible(true);
//$("#window").swidget().center();
}
function initializeWindowWidgets() {
$("#window").shieldWindow({
position: { left: 500, top: 200 },
width: 320,
height: 360,
title: "Insertar abastecimiento",
modal: true,
visible: false
});
$("#solId").shieldNumericTextBox({
});
$("#atmid").shieldTextBox({
});
$("#fechaAbastecimiento").shieldDatePicker({
});
$("#cargar").shieldCheckBox({
});
$("#emergencia").shieldCheckBox({
});
$("#save").shieldButton({
events: {
click: function (e) {
var grid = $("#grid").swidget(),
editedItem = grid.dataSource.edit(3).data;
editedItem.solId = $("#solId").swidget().value();
editedItem.atmid = $("#atmid").swidget().value();
grid.saveChanges();
$("#window").swidget().close();
}
}
});
Also I can get the row data when I select a row using:
selectionChanged: function (e) {
var selected = e.target.contentTable.find(".sui-selected");
if (selected.length > 0) {
message.innerHTML = selected.get(0).innerHTML;
}
else {
message.innerHTML = "";
}
}
Finally I know how to call a service for example:
$("#grid").shieldGrid({
dataSource: {
events: {
error: function (event) {
if (event.errorType == "transport") {
// transport error is an ajax error; event holds the xhr object
alert(JSON.stringify(event));
alert("transport error: " + event.error.statusText);
// reload the data source if the operation that failed was save
if (event.operation == "save") {
this.read();
}
}
else {
// other data source error - validation, etc
alert(event.errorType + " error: " + event.error);
}
},
},
remote: {
read: {
type: "POST",
url: "abastecimientos/get",
contentType: "application/json",
dataType: "json"
},
modify: {
create: function (items, success, error) {
var newItem = items[0];
$.ajax({
type: "POST",
I need to do these tasks:
Select a row in my grid.
Press insert button.
Shown my custom window with the row's data.
Modify the data showed.
Press a save button and call a remote service in order to insert new row.
I know how to do these tasks separately but tasks 3 and 5 are not clear to me.
I google all internet but I can't figure out how to do it.
Please I would appreciate any suggestion.
Juan
Did you check the following Shield UI demos?
3. Shown my custom window with the row's data
5. Press a save button and call a remote service in order to insert new row
I have been using this example to make a diagram with Alloyui, but I don't find the way to make a custom node in JAVA.
I've tried to simply add it in AvaliableFields, but doesn't seem to work:
diagramBuilder.setAvailableFields(
new NodeType(
"diagram-node-custom-icon",
"Custom",
"custom"
));
I have already done this in another example, directly in the javascript and works:
Y.DiagramNodeCustom = Y.Component.create({
NAME: 'diagram-node',
ATTRS: {
type: {
value: 'custom'
},
myAtt: {
validator: Y.Lang.isString,
value: ''
},
myAtt2: {
validator: Y.Lang.isString,
value: ''
}
},
EXTENDS: Y.DiagramNodeTask,
prototype: {
getPropertyModel: function () {
var instance = this;
var model = Y.DiagramNodeTask.superclass.getPropertyModel.apply(instance, arguments);
model.push({
attributeName: 'myAtt',
name: '123'
});
model.push({
attributeName: 'myAtt2',
name: '456'
});
return model;
}
}
});
But I'm trying only to touch the java part. Any ideas?
Seems like this add-on doesn't accept custom nodes, so I am working with Javascript.
Here's an example, I hope it helps you:
var Y = YUI().use(
'aui-diagram-builder',
function (Y) {
Y.DiagramNodeCustom = Y.Component.create({
NAME: 'diagram-node',
ATTRS: {
type: {
value: 'custom'
},
customAttr: {
validator: Y.Lang.isString,
value: 'A Custom default'
}
},
EXTENDS: Y.DiagramNodeTask,
prototype: {
getPropertyModel: function () {
var instance = this;
var model = Y.DiagramNodeTask.superclass.getPropertyModel.apply(instance, arguments);
model.push({
attributeName: 'customAttr',
name: 'Custom Attribute'
});
return model;
}
}
});
Y.DiagramBuilder.types['custom'] = Y.DiagramNodeCustom;
var availableFields = [{
iconClass: 'diagram-node-start-icon',
label: 'Start',
type: 'start'
}, {
iconClass: 'diagram-node-task-icon',
label: 'Task',
type: 'task'
}, {
iconClass: 'diagram-node-custom-icon',
label: 'Custom',
type: 'custom'
}, {
iconClass: 'diagram-node-end-icon',
label: 'End',
type: 'end'
}];
diagram = new Y.DiagramBuilder({
availableFields: availableFields,
boundingBox: '#myDiagramContainer',
srcNode: '#myDiagramBuilder'
}).render();
});
.diagram-node-custom .diagram-node-content {
background: url(http://a.deviantart.net/avatars/m/e/mercedes77.gif?5) no-repeat scroll center transparent;
}
.diagram-node-custom-icon {
background: url(http://dribbble.s3.amazonaws.com/users/1266/screenshots/213334/emoticon-0188-nyancat.gif) no-repeat scroll center transparent;
}
<div id="myDiagramContainer">
<div id="myDiagramBuilder" width=100></div>
</div>
<button id="myButton"></button>
See also https://github.com/mstahv/diagram-builder
I'm still new with jsTree, JavaScript and jQuery functions.
My problem is that I need to refresh the header so when I click certain nodes in jstree the header will be refreshed.
The jstree is located in applet.jsp and the function for refreshing the header is located in header.jsp.
How can I call the refresh method for refreshing inside jstree?
This is my jstree in applet.jsp:
var selected_folder = "folder_${user.defaultFolder}";
$(document).ready(function() {
jQuery("#folder_tree").jstree({
"xml_data" : {
"ajax" : {
"url" : "<%=request.getContextPath()%>" + "/ListFolder.action"
},
"xsl" : "nest"
},
"ui" : {
"initially_select" : [ "#folder_${user.defaultFolder}" ]
},
"types" : {
"types" : {
"leaf" : {
"icon" : {
"image" : "<%=request.getContextPath()%>/images/icons/leaf.jpg"
}
},
"share" : {
"icon" : {
"image" : "<%=request.getContextPath()%>/images/icons/share.jpg"
}
}
}
},
"themes" : {
"theme" : "msam"
},
"plugins" : [ "themes", "xml_data", "ui", "types" ]
});
jQuery("#folder_tree").bind('loaded.jstree', function() {
jQuery("#folder_tree").jstree('open_all');
});
jQuery("#folder_tree").bind("select_node.jstree", function(e, data) {
var haveContent = data.rslt.obj.attr("haveContent");
if (haveContent === 'false') {
return;
}
var id = data.rslt.obj.attr("id");
id = id.substring("folder_".length);
parent.content.location.href = "<%=request.getContextPath()%>"
+ "/home/Folder.action?folderID="
+ id;
//alert(data.inst.get_text(data.rslt.obj)); // NODE TEXT
$.ajax({
url : "<%=request.getContextPath()%>" + "/WebContent/home/header.jsp",
data :{folderId,id},
cache:false,
success : function(data){
setupTree(data); //put your logic to set tree inside a method called setupTree or whatever you want to call it.
}
});
});
jQuery("#folder_tree").bind("refresh.jstree", function (event, data) {
jQuery("#folder_tree").jstree("select_node", selected_folder);
});
});
var tree_select_node = function(id) {
selected_folder = "#folder_" + id;
jQuery("#folder_tree").jstree("deselect_all");
jQuery("#folder_tree").jstree("refresh");
}
And this is the method/function for refreshing the header in header.jsp:
function selectHeaderLink(selectedLinkID) {
var linkIDArray = new Array('homeLink', 'newFolderLink', 'settingsLink', 'reportsLink');
resetHeaderLinks(linkIDArray, 'tab_link');
if(linkIDArray.length > 0) {
for(var i=0;i<linkIDArray.length;i++) {
if(linkIDArray[i] == selectedLinkID) {
var myLink = document.getElementById(linkIDArray[i]);
var row = myLink.parentNode;
row.style.height = "28";
row.style.backgroundImage = 'url(../images/bg-topmenu.jpg)' ;
myLink.style.color = "white";
break;
} //--end: if-for-if
} //--end: for-if
} //--end: if
}
function windowOnload(){
selectHeaderLink('homeLink');
}
I already tried using an ajax request but I'm still confused where to put this ajax request.
Sorry for my bad English. I hope someone will help me with this problem.
i already find the answer
jQuery("#folder_tree").bind("select_node.jstree", function(e, data) {
var haveContent = data.rslt.obj.attr("haveContent");
if (haveContent === 'false') {
return;
}
selectHeaderLink('homeLink');
var id = data.rslt.obj.attr("id");
id = id.substring("folder_".length);
parent.content.location.href = "<%=request.getContextPath()%>"
+ "/home/Folder.action?folderID="
+ id;
//alert(data.inst.get_text(data.rslt.obj)); // NODE TEXT
});
i just put the function into the jquery n then remove the function to centralize js file..and its work..
I have a store and a FormPanel. I want to send data from the FormPanel to a server:
var store_form=null;
store_form = new Ext.data.Store({
url: url_servlet+"kadastr_zemform.jsp",
reader: new Ext.data.XmlReader({
totalProperty: "results",
record: "contact",
fields: [
]}),
});
});
store_form.load();
Panel
var podform = new Ext.FormPanel({
labelAlign: 'left',
id: 'tab_6',
frame:true,
title: 'Договоры подряда',
bodyStyle:'padding:5px 5px 0',
width: 600,
reader: new Ext.data.XmlReader({}),
listeners: {
'activate' : function(pod_form,records,options) {
console.log("store:"+store_form);
this.loaded = true;
//alert("loaded");
//console.log(store.getAt(0));
var record = store_form.getAt(0);
podform.getForm().loadRecord(record);
}
},
fields[]
});
podform.addButton({
text: 'Submit',
//disabled:true,
handler: function(){
podform.getForm().submit({url:url_servlet+'submit.jsp', waitMsg:'Saving Data...', submitEmptyText: false});
}
});
In firebug I can see that nothing is sent to the server. What am I doing wrong?
Another question: what can I do on the server side to get this data?
UPDATE
I forgot to add XMLReader to form. But nothing has changed.
UPDATE2
Now parameters are sent to the server:
But I am getting an error:
SyntaxError: syntax error
...ayer=a;this.activate()}else{this.layer=a}},setTargets:function(b){this.targets=[...
I am trying to pass a user defined parameter to the Java Controller which acts as a data source to my jquery Data-Table.
The point is, i want to do this (pass the parameter) on a change event for a combobox on my jsp.
Here is my datatable initialization:
var oTable = $('#reqAllQueriesTable')
.dataTable(
{
"sDom": '<"H"l<"projectTeamTools">frtip>',
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "query/getQuery",
"bPaginate" : true,
"bLengthChange": true,
"bScrollCollapse" : true,
"iDisplayLength" : 10,
"bFilter" : true,
"bJQueryUI" : true,
"sPaginationType" : "full_numbers",
"sSearch": "Search"
});
My combobox whose values are to be passed to the controller and the respective functions are:
$("div.projectTeamTools").html('Organize by Project Teams: <select id="projectTeams"><option value="0">Project Team</option><option value="1">All</option><option value="2">Not Associated</option><c:forEach var="projectTeam" items="${userProjectTeams}"><option value="${projectTeam.projectId}">${projectTeam.projectName}</option></c:forEach></select>');
$("#projectTeams").change(function () {
onTeamSelect($(this).val());
});
function onTeamSelect(teamId){
alert(teamId +" Selected");
//This function to pass the parameter to the datatable is supposed to be here.
oTable.fnDraw();
}
The datatable then displays the new data it receives from the ajax Source getQuery.
PS: I cannot use fnServerParams as I am using the older version of datatables. I have tried using fnServerData but it did not help. I guess I am wrong in the way I am using the ajax function in fnServerData.
"fnServerData": function ( sSource, aoData, fnCallback ) {
$("#projectTeams").change(function() {
aoData.push( { "name": "myParam", "value": $("#ComboBox option:selected").value() } );
$.ajax( {
"dataType": 'json',
"url": sSource,
"data": aoData,
"success": fnCallback
});
I cannot see the parameter I want to pass in the 'Network XHR' in my browser when I select an item from the combo-box.
Please help!
Got an answer. During initialization, fnServerData should be:
"fnServerData": function ( sSource, aoData, fnCallback ) {
aoData.push( { "name" : "myTeamId", "value" : myTeamId } );
$.getJSON( sSource, aoData, function (json) {
fnCallback(json);
});
}
and the onChange function of the combobox on which I want to pass the parameter:
$("#projectTeams").change(function () {
onTeamSelect($(this).val());
});
function onTeamSelect(teamId){
myTeamId = teamId;
oTable.fnDraw();
}
where myTeamId is a global variable.
The oTable.fnDraw() redraws the datatable and assigns the value of teamId to the myTeamId, which I use in fnServerData.
This code worked for me!