How to add multiple models to collection in Backbone - javascript

How to add multiple models to collection in Backbone
formatChannelIds: function() {
_this = this;
// var activeIds ='';
_.filter(_this.modelChannelList.toJSON(), function(channelObj) {
if (channelObj['isactive'] == true) {
// activeIds =activeIds+','+channelObj['id'];
console.log(channelObj['id']);
_this.modelChannelStats.fetch({
data: {
channel: channelObj['id']
},
processData: true
}, {
success: function(model, response, options) {
_this.channelstatsCollection.push(model);
}
});
}
});
console.log(_this.channelstatsCollection);
console.log(_this.modelChannelStats);
}
My collection shows a null in the Array.

Fetch method accepts one object containing all necessary params.
_this.modelChannelStats.fetch({
data: {
channel: channelObj['id']
},
processData: true,
success: function(model, response, options) {
_this.channelstatsCollection.push(model);
}
});
Try to use this piece of code.

Related

Why is [object Object] viewed in column when trying to bind columns in MVC

This is the JS I call in Index on document ready
jsonfields = #Html.Raw(Json.Encode(ViewBag.ColumnData));
This is the Ajax Call which I Make to bind
function onTeamTreeLoad(e) {
try {
$.ajax({
type: "POST",
url: window.ApplicationPath + 'Generic/GetTeamTree',
dataType: "json",
headers: { "__RequestVerificationToken": $("#AntiForgeryToken").val() },
contentType: 'application/json',
success: function (data) {
if (data != null) {
$("#TeamName").kendoDropDownTree({
dataSource: {
schema: {
model: {
children: "Items"
}
},
data: data
},
dataTextField: "Text",
dataValueField: "Id"
});
try {
if (e.model.TeamName !== "") {
$("#TeamName").data("kendoDropDownTree").text(e.model.TeamName);
}
} catch (e) { }
}
},
error: function () {
console.log('Failed to load');
}
});
} catch (e) {
console.log(e);
}
}
Why am I seeing [objectObject] when trying to bind the column? I want the data to be viewed instead of objectObject. I tried adding SerializeObject method to ID and Text but then I could not view that column when editing! I would like to know if there is any mistake in the AJAX call and what are the things that need to be added if using SerializeObject or JSON.Stringify.
Here you are just printing object. So Object -> Stringify give output like [object Object].
You can try this code.
for(var prop in obj) {
console.log(obj[prop]);
}

How can i fix my module pattern to work

I have a module in a different file which should essentially carry out my ajax requests for me (this is in ajaxCall.js), I am trying to add this module to the global window object so that i can use it in another file called (basket-page.js), but I get an error stating
Uncaught TypeError: Cannot read property 'process' of undefined(…)
AjaxCall.js
"user strict";
window.ajaxCall = window.ajaxCall || {}
var ajaxCall = (function () {
var api = {
process: function (destinationUrl, dataToPost, callbackFunction) {
$.ajax({
url: destinationUrl,
data: dataToPost,
method: "POST",
dataType: "JSON",
success: function (data) {
if (element.length > 0) {
callbackFunction(data, element);
}
},
error: function (req, status, errorObj) {
console.log(status);
}
});
}
}
window.ajaxCall = api;
return api;
})();
basket-page.js
"use strict";
basket = basket || {};
var basket = (function (ajax) {
var api = {
init: function () {
$("#tblBasket").dataTable({
bFilter: false,
pageLength: 10,
paging: true,
autoWidth: true,
columns:
[
{ "orderDataType": "dom-text", type: "string" },
{ "orderDataType": "dom-text-numeric" },
null
],
fixedColumns: true
});
},
removeBasketProductRow: function (data, element) {
if (data === true) {
element.remove();
}
}
};
$("#btnRemoveBasketProduct").click(function() {
var product = $(this).closest("tr");
var productId = product.attr("id");
window.ajaxCall.process("/Products/RemoveBasketProduct", productId, api.removeBasketProductRow);
});
return api;
})(window);
$(document).ready(function () {
basket.init();
});
Remove all the function wrapping. It's unnecessary.
"user strict";
window.ajaxCall = {
process: function (destinationUrl, dataToPost, callbackFunction) {
$.ajax({
url: destinationUrl,
data: dataToPost,
method: "POST",
dataType: "JSON",
success: function (data) {
if (element.length > 0) {
callbackFunction(data, element);
}
},
error: function (req, status, errorObj) {
console.log(status);
}
});
}
}
The issue was making sure i had my other script file loaded already, since this is what adds object to the global window object.

Kendo UI, datagrid inserted row produces request multiple times

i have problem with Kendo data grid component.
I'm trying to add new row into grid and create remote request to API via create event.
Problem is that if i try to add new row after first request Kendo make 2 requests instead of the one.
I tried to find some solution for this using transport create and options.success method but without luck.
http://docs.telerik.com/kendo-ui/api/framework/datasource#configuration-transport.create
Could somebody tell to me what i'm doing wrong?
Thanks for any help.
Here is the code of the server response for create:
+ Response 200 (application/json)
{
"status": "OK",
"result":[
{
"id":22,
"username":"blahblah",
"name":"Thomas",
"surname":"Man",
"email":"to.mas.marny#gmail.com",
"created":"1399986964",
"role":"USER"
}
]
}
Here is the code of the method:
$scope.initGrid = function () {
// get access token from localstorage
var token = localStorage
.getItem($rootScope.lsTokenNameSpace);
// set pagination data
var paginationData = {
"token": token,
"data": {
"page": 1,
"items_per_page": 20
}
};
var dataPacket;
dataPacket = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
url: $rootScope.apiBaseUrl + "user/list",
dataType: "json",
type: "POST",
data: JSON
.stringify(paginationData),
success: function (
response) {
console
.log("List of users succesfully obtained");
console
.log(response.result);
// pass response to
// model
options
.success(response);
// $notification.enableHtml5Mode();
},
error: function (error) {
console
.log("user list request error");
console.log(error);
$notification
.error(
"User list cannot be loaded",
"Please try again in a minute.");
}
});
},
update: function (options) {
console.log("Update");
options
.success("{\"test\":\"test\"}");
},
destroy: function (options) {
console.log("destroy");
options
.success("{\"test\":\"test\"}");
},
create: function (options) {
console.log("Create");
console.log(options.data);
$.ajax({
url: $rootScope.apiBaseUrl + "user/create",
dataType: "json",
type: "POST",
data: JSON
.stringify(options.data),
success: function (
response) {
console
.log("New user created");
console
.log(response.status);
// pass response to
// model
options
.success(response.result);
// $notification.enableHtml5Mode();
},
error: function (error) {
console.log("user list request error");
console.log(error);
$notification
.error(
"User cannot be created",
"Please try again in a minute.");
}
});
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
//batch : true,
//autoSync: true,
schema: {
data: "result",
model: {
id: "id",
fields: {
id: {
editable: false,
nullable: true
},
name: {
editable: true,
nullable: false
},
username: {
editable: true,
nullable: false
}
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataPacket,
filterable: true,
pageSize: 20,
pageable: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: ["id", "name", "username", {
command: ["edit", "destroy"],
title: " ",
width: "200px"
}],
editable: "inline"
});
};
If you declare id inside model then you don't have to declare id inside model fields.
Also when you point
data: "result"
for the model you have to pass
options.success(response)
inside ajax's success function, not just
options.success(response.result)
I think if null is passed to the Datasource of the kendo Grid in the html helper, the Grid will be built in “remote data mode” rather than “local data mode”
and since the read Url is not set the current browser Url will be used for the read operation.
make sure to initialize the list in the Model before using it as a Datasource.

How to trim JSON Object removing whitespace

I hava a common ajax.post method which accepts data from function parameter. Now i want to trim the properties of data. Below is the code.
function PostToServer(options) {
var defaults = {
'url': null,
'data': null,
'onSuccess': null,
'onError': null
};
var parameters = $.extend(defaults, options);
$.ajax({
url: parameters.url,
type: "POST",
data: JSON.stringify(parameters.data),
contentType: "application/json",
success: function (res) {
if ($.isFunction(parameters.onSuccess)) {
parameters.onSuccess(res);
}
},
error: function (xhr, status, error) {
if ($.isFunction(parameters.onError)) {
parameters.onError(xhr, status, error);
}
}
});
}
Now in this function i want to trim the 'parameters.data' object so that it removes whitespace from both ends. but i dont know what comes in 'parameters.data' so i can not access its properties and use trim function.
Please help.
Try this:
$.each(res, function(index) {
var that = this;
$.each(that, function(key, value) {
var newKey = $.trim(key);
if (typeof value === 'string')
{
that[newKey] = $.trim(value);
}
if (newKey !== key) {
delete that[key];
}
});
});

Backbone collection not triggering add event on fetch

I have been banging my head against a wall for hours on this one....
Looked at many-a-page and I feel like I have my script correct, but my collection is not triggering an add event with add: true passed in the fetch method. I can bind to the reset event, but the add event doesn't trigger..
Model:
test.Models.AppBlock = Backbone.Model.extend({
defaults: {
AppID: null,
AppName: null,
AppDescription: null
},
idAttribute: "AppID"
});
Collection:
test.Collections.AppBlock = Backbone.Collection.extend({
model: test.Models.AppBlock,
url: ApiPath + "apps/byuser",
Loading: false,
initialize: function () {
},
getAppBlocks: function () {
if (!this.Loading) {
this.Loading = true;
this.fetch({
data: JSON.stringify({
Token: test.Session.Token
}),
add: true, // OMG WTF ?!?!
type: 'POST',
dataType: 'json',
contentType: 'application/json',
cache: false,
success: this.getAppBlocksSuccess,
error: this.getAppBlocksError
});
}
},
parse: function (response) {
return response.Data;
},
getAppBlocksSuccess: function (that, response) {
},
getAppBlocksError: function (that, response) {
}
});
View:
test.Views.DashboardLatestMain = Backbone.View.extend({
Loading: null,
initialize: function () {
this.template = _.template(test.Templates.DashboardLatestMain);
this.collection.bind('add', this.addAppBlock);
this.render();
},
render: function () {
$('#latest').prepend(this.template);
this.Loading = new test.Views.Loading({
el: '.main'
});
this.collection.getAppBlocks();
},
addAppBlock: function (appBlockModel) {
alert(appBlockModel); // no dice....
var appBlockView = new test.Views.AppBlock({
model: appBlockModel,
el: '#latest .main h3',
After: true
});
}
});
Any help is greatly appreciated.
edit
Data returned from api:
{
"Status":["1","OK"],
"Data":[{"AppID":1,"AppName":"test","AppDescription":"test"},
{"AppID":2,"AppName":"test","AppDescription":"test"}]
}
In Backbone 0.9.9 collection's fetch did a reset by default, which triggered only the 'reset' event. In 1.0, fetch does an update (now called set), and triggers 'add', 'remove' and 'change' events by default.
So, either update to 1.0 and your existing code should work. Or, add update:true to your fetch call (you don't need add:true then because that is the default).

Categories

Resources