Tried the following:
var collectionList = users.fetch();
alert(collectionList);
This returns null despite there being models in it.
Update - this worked for me:
users.fetch({
success: function() {
console.log(users.toJSON());
},
error: function() {
// something is wrong..
}
});
users.fetch({
success: function(response) {
_.each(response.models, function(model) {
//Do something with the model here
});
}
});
users.fetch().then(function () {
console.log(users.toJSON());
});
http://backbonejs.org/#Collection-fetch
Fetch is an async method, so is empty upon being called, after you specify success and error you should be able to then list your models.
users.fetch({
success: function() {
console.log(users.toJSON());
},
error: function() {
// something is wrong..
}
});
This one also can
var that = this;
users.fetch({
success: function(collection, response) {
console.log(that.collection.toJSON());
},
error: function() {
// something is wrong..
}
});
Related
I have a site developed in cakephp where I'm using a simple app in backbone.
Now I would like to save data from backbone but doesn't work, return always inside callback error, and it doens't take the right value to save inside table.
This is my simple app:
TaskModel = Backbone.Model.extend({
url: function(){
return "/step_task/ajax_save";
}
});
TaskCollection = Backbone.Collection.extend({
model: TaskModel,
initData: function(data){
return data;
}
});
var TaskView = Backbone.View.extend({
template: _.template($("#task-template").html()),
initialize: function(){
this.task = new TaskCollection(<?php echo json_encode($step['StepTask']); ?>);
this.render();
},
render: function(){
taskModel = new TaskModel({
'id': '1',
'user_id': '1'
});
//--------------------------- here I would like to save inside my table ----------------
taskModel.save(null, {
success: function(model, response) {
console.log('success');
console.log(model);
console.log(response);
},
error: function(model, response) {
console.log('error');
console.log(model);
console.log(response);
},
wait: true // Add this
});
$(this.el).html(this.template({tasks: this.task.models}));
}
});
and this is my funciton inside StepTaskController.php
public function ajax_save(){
$this->autoRender = false;
$this->StepTask->save($this->request->data);
}
How can I solve it?
Try to change the url in your model to urlRoot :
TaskModel = Backbone.Model.extend({
urlRoot: '/step_task/ajax_save'
});
I have a dojo class like this.
var widget = declare("app.util",null, {
createSecuredLayers: function () {
$.ajax.get({
url: "/Api/GetLayer",
success: function (e) {
},
error: function () {
}
});
}
});
I want to use this object with callback parameters. I mean I want to pass success and error callbacks as parameter.
var util = new app.util();
util.createSecuredLayers({
success:function(){ },
error:function(){ }
});
createSecuredLayers: function(item) {
$.ajax.get({
url: "/Api/GetLayer",
success: item.successCallback,
error: item.errorCallback
});
}
When you call the method, don't forget to pass the response in the success callback.
util.createSecuredLayers({
successCallback: function(resp) {},
errorCallback: function(err) {}
});
You can do it like this:
var widget = declare("app.util",null, {
createSecuredLayers: function (args) {
$.ajax.get({
url: "/Api/GetLayer",
success: args.success,
error: args.error
});
}
});
var util = new app.util();
util.createSecuredLayers({
success:function(){ },
error:function(){ }
});
You should also consider using Dojo's deferred
I have been using knockout.js for a while now, and haven't encountered this problem before. Usually, when I try to push a new js object to an observableArray, it works without an issue, but for some reason, this time around I'm getting this error:
TypeError: self.Students.push is not a function
Here is a snippet of my code:
window.ApiClient = {
ServiceUrl: "/api/students",
Start: function () {
var viewModel = ApiClient.ViewModel(ngon.ClientViewModel);
ko.applyBindings(viewModel);
viewModel.get();
}
};
ApiClient.ViewModel = function(data) {
var self = this;
ko.mapping.fromJS(data, {}, this);
this.get = function (id) {
if (id == undefined) {
return ApiClient.Service.get(self.PageSize(), self.PageNumber(), function (data) {
self.Students(data);
});
}
}
this.post = function () {
return ApiClient.Service.post(self.DetailedStudent, function (data) {
self.Students.push(data);
});
}
return this;
}
ApiClient.Service = function () {
var _get = function (pageSize, pageNumber, callback) {
sv.shouldShowLoading = false;
var queryParams = String.format("?pageSize={0}&pageNumber={1}", pageSize, pageNumber);
$.ajax(ApiClient.ServiceUrl + queryParams, {
dataType: "json",
type: "get",
success: callback
});
}
var _post = function (student, callback) {
$.ajax(ApiClient.ServiceUrl, {
data: ko.mapping.toJSON(student),
type: "post",
contentType: "application/json; charset-utf-8",
statusCode: {
201 /*Created*/: callback,
400 /*BadRequest*/: function (jqxhr) {
var validationResult = $.parseJSON(jqxhr.responseText);
alert(jqxhr.responseText);
}
}
});
}
return {
get: _get,
post: _post
};
}();
$(document).ready(function () {
ApiClient.Start();
});
My student object is a very simple C# object that has Id, FirstName, LastName. The get() function works without any issues, it's just the callback function from the post() that cannot push the resulting data. Also, the data being returned back from the server looks correct:
{"Id":"rea","FirstName":"asdf","MiddleName":null,"LastName":"rrr"}
I solved this! It's because the initial viewModel, when being instantiated by the page's view model object had 'null' for its Students property.
knockout.js requires non-null values for all fields that are to be auto mapped.
I have following code:
App.Views.UseCategory = Backbone.View.extend({
template: HandlebarsTemplates['uses/useCategory'],
initialize: function() {
_.bindAll(this, 'render', 'addCategory');
this.render();
},
events: {
'submit #addCategoryForm': 'addCategory'
},
render: function() {
$(this.el).append(this.template(this.options));
return this;
},
addCategory: function(event) {
event.preventDefault();
var self = this;
var useCategoryId = $('select[id=use_category_id]').val();
this.model.set('category_id', parseInt(useCategoryId,10));
this.model.save({ success: console.log('success') });
}
});
Code above works and trigger success callback, so I receive in console "success".
But why when I change that addCategory function to:
addCategory: function(event) {
event.preventDefault();
var self = this;
var useCategoryId = $('select[id=use_category_id]').val();
this.model.set('category_id', parseInt(useCategoryId,10));
console.log('save?');
this.model.save({ success: this.addedCategory, error: function() { console.error(arguments) } });
},
addedCategory: function() {
console.log('success');
}
success callback is not triggered anymore, why?
Edit:
When you do:
this.model.save({ success: console.log('success') });
You already call your console log. What you should do is (not the same):
this.model.save({ success: function() {
console.log('success')
} });
Do you understand the difference or do you need clarifications?
In fact i suspect your success callback is never called.
EDIT:
model.save(data, opts) takes two arguments. You should do:
this.model.save({}, { success: function() {
console.log('success')
} });
In my router I have
routes: {
"create/:type": "create",
// #create/modeltype
"diagram/:id": "diagram",
// #diagram/193
"": "list"
//
},
then i have the create route
create: function(type) {
console.log("diagram create " + type.toUpperCase());
var newDiagram = new Diagram({
type: type.toUpperCase()
});
newDiagram.save({}, {
success: function(model, response) {
console.log("save diagram success");
window.vnb.routers.workspace.navigate("diagram/" + model.get("id"), true);
},
error: function(model, response) {
console.log("error");
console.log(model);
console.log(response);
}
});
},
If someone creates a model and then clicks back, they create another model, i would like this to not happen.
You can make the newDiagram variable into a property on the router called diagram. Then you can instantiate it the first time the create method is called, and the following calls to the create method can use the variable.
Here's an example
create: function(type) {
console.log("diagram create " + type.toUpperCase());
if (this.diagram === undefined) {
this.diagram = new Diagram({
type: type.toUpperCase()
});
}
this.diagram.save({}, {
success: function(model, response) {
console.log("save diagram success");
window.vnb.routers.workspace.navigate("diagram/" + model.get("id"), true);
},
error: function(model, response) {
console.log("error");
console.log(model);
console.log(response);
}
});
},