Backbone fetch success and error function issue - javascript

I've a fetch method on a collection. The callback function success and error is never called but the fetch happens correctly and fill the collection. It seems very strange.
var TweetsCollection= new Tweets();
TweetsCollection.fetch({
success:function (tweets){<---never called
alert("ok");
},
error:function(c){<---never called
alert("ko");
}
});
console.log(TweetsCollection);<---- collection correctly filled
and this is the fetch methof od TweetsCollection:
fetch: function(options) {
var collection = this;
var params = {
user_id: this.query,
page:this.page
};
cb.__call(
"statuses_userTimeline",
params,
function (reply) {
// console.log(reply);
collection.reset(reply);
// return reply;
}
);
}

You don't have to override the fetch method.
If you want to add extra logic to the sync process, you override the sync method.

Related

get Alfresco.util.Ajax.request response.json data from external function

I have an alfresco webscript who return a json response.
I have a js function getWorkflowRepositoryContent() who call this webscript and get the data retuned in the response.
I store the response.json in an array list.
All works fine for me, but when i call getWorkflowRepositoryContent() from another js function, it returned an empty array when it must return an array containing the data received from webscript response.
There is the function where i return the data received from the webscript.
Can you tell me what i made a mistake, or tell me how to properly return the data from that function.
function getWorkflowRepositoryContent(){
var list=[];
var workflowFilesNameAndNodeRef;
var test=function getWorkflowFilesList(response)
{
workflowFilesNameAndNodeRef=response.json.nodes;
$.each(response.json.nodes,function(index,value){
list.push(value.name);
});
}
Alfresco.util.Ajax.request(
{
method:Alfresco.util.Ajax.GET,
url: Alfresco.constants.PROXY_URI + "/ALFRESCO-DIRECTORY",
successCallback:
{
fn:test,
scope:this
},
failureCallback:
{
fn: function(response)
{
Alfresco.util.PopupManager.displayMessage({text:"Failure"});
},
scope: this
}
});
console.log(list.length);
return list;
}
Your getWorkflowRepositoryContent is getting asynchronous data but returning synchronously so your example won't work.
An easy way would be to simple call your function with a callback argument.
function getWorkflowRepositoryContent(cb){ // pass a callback as an argument
var list=[];
var workflowFilesNameAndNodeRef;
var test=function getWorkflowFilesList(response)
{
workflowFilesNameAndNodeRef=response.json.nodes;
console.log(response.json.nodes);
$.each(response.json.nodes,function(index,value){
list.push(value.name);
});
$.each(list,function(index, fileName){
$('<option/>').val(fileName).html(fileName).appendTo('#saveButton');
$('<option/>').val(fileName).html(fileName).appendTo('#loadButton');
});
cb(list); // call the callback once the work is done
}
Alfresco.util.Ajax.request(
{
method:Alfresco.util.Ajax.GET,
url: Alfresco.constants.PROXY_URI + "/ALFRESCO-DIRECTORY",
successCallback:
{
fn:test,
scope:this
},
failureCallback:
{
fn: function(response)
{
Alfresco.util.PopupManager.displayMessage({text:"Failure To get StarXpert Workflow content"});
},
scope: this
}
});
}
getWorkflowRepositoryContent( function(list) {
console.log(list);
});
You could also use promises but it might be a little harder if you're not familiar with them.

Meteor Router data function being called twice

I have a router data function that calls a Meteor method to insert a new document into a collection. I noticed that the document was being inserted twice and then I noticed that the data function itself is called twice every time the route is visited. I can't figure out why this is happening.
Router.route('/myurl',{
name: 'myurl',
path: '/myurl',
data: function () {
console.log('dupe?');
// the data function is an example where this.params is available
// we can access params using this.params
// see the below paths that would match this route
var params = this.params;
// we can access query string params using this.params.query
var post = this.params.query;
// query params are added to the 'query' object on this.params.
// given a browser path of: '/?task_name=abcd1234
// this.params.query.task_name => 'abcd1234'
if(this.ready()){
Meteor.call('points.add', post, function(error, result){
if(error)
{
Session.set("postResponse", "failed");
}
else
{
Session.set("postResponse", "success");
}
});
return {_message: Session.get("postResponse")};
}
}
});
I was able to fix this by moving everything under data to a Router.onRun hook.

Ember Understand execution flow between route/controller

I have a "box" route/controller as below;
export default Ember.Controller.extend({
initialized: false,
type: 'P',
status: 'done',
layouts: null,
toggleFltr: null,
gridVals: Ember.computed.alias('model.gridParas'),
gridParas: Ember.computed('myServerPars', function() {
this.set('gridVals.serverParas', this.get('myServerPars'));
this.filterCols();
if (!this.get('initialized')) {
this.toggleProperty('initialized');
} else {
Ember.run.scheduleOnce('afterRender', this, this.refreshBox);
}
return this.get('gridVals');
}),
filterCols: function()
{
this.set('gridVals.layout', this.get('layouts')[this.get('type')]);
},
myServerPars: function() {
// Code to set serverParas
return serverParas;
}.property('type', 'status', 'toggleFltr'),
refreshBox: function(){
// Code to trigger refresh grid
}
});
My route looks like;
export default Ember.Route.extend({
selectedRows: '',
selectedCount: 0,
rawResponse: {},
model: function() {
var compObj = {};
compObj.gridParas = this.get('gridParas');
return compObj;
},
activate: function() {
var self = this;
self.layouts = {};
var someData = {attr1:"I"};
var promise = this.doPost(someData, '/myService1', false); // Sync request (Is there some way I can make this work using "async")
promise.then(function(response) {
// Code to use response & set self.layouts
self.controllerFor(self.routeName).set('layouts', self.layouts);
});
},
gridParas: function() {
var self = this;
var returnObj = {};
returnObj.url = '/myService2';
returnObj.beforeLoadComplete = function(records) {
// Code to use response & set records
return records;
};
return returnObj;
}.property(),
actions: {
}
});
My template looks like
{{my-grid params=this.gridParas elementId='myGrid'}}
My doPost method looks like below;
doPost: function(postData, requestUrl, isAsync){
requestUrl = this.getURL(requestUrl);
isAsync = (isAsync == undefined) ? true : isAsync;
var promise = new Ember.RSVP.Promise(function(resolve, reject) {
return $.ajax({
// settings
}).success(resolve).error(reject);
});
return promise;
}
Given the above setup, I wanted to understand the flow/sequence of execution (i.e. for the different hooks).
I was trying to debug and it kept hopping from one class to another.
Also, 2 specific questions;
I was expecting the "activate" hook to be fired initially, but found out that is not the case. It first executes the "gridParas" hook
i.e. before the "activate" hook. Is it because of "gridParas"
specified in the template ?
When I do this.doPost() for /myService1, it has to be a "sync" request, else the flow of execution changes and I get an error.
Actually I want the code inside filterCols() controller i.e.
this.set('gridVals.layout', this.get('layouts')[this.get('type')]) to
be executed only after the response has been received from
/myService1. However, as of now, I have to use a "sync" request to do
that, otherwise with "async", the execution moves to filterCols() and
since I do not have the response yet, it throws an error.
Just to add, I am using Ember v 2.0
activate() on the route is triggered after the beforeModel, model and afterModel hooks... because those 3 hooks are considered the "validation phase" (which determines if the route will resolve at all). To be clear, this route hook has nothing to do with using gridParas in your template... it has everything to do with callling get('gridParas') within your model hook.
It is not clear to me where doPost() is connected to the rest of your code... however because it is returning a promise object you can tack on a then() which will allow you to essentially wait for the promise response and then use it in the rest of your code.
Simple Example:
this.doPost().then((theResponse) => {
this.doSomethingWith(theResponse);
});
If you can simplify your question to be more clear and concise, i may be able to provide more info
Generally at this level you should explain what you want to archive, and not just ask how it works, because I think you fight a lot against the framework!
But I take this out of your comment.
First, you don't need your doPost method! jQuerys $.ajax returns a thenable, that can be resolved to a Promise with Ember.RSVP.resolve!
Next: If you want to fetch data before actually rendering anything you should do this in the model hook!
I'm not sure if you want to fetch /service1, and then with the response you build a request to /service2, or if you can fetch both services independently and then show your data (your grid?) with the data of both services. So here are both ways:
If you can fetch both services independently do this in your routes model hook:
return Ember.RSVP.hash({
service1: Ember.RSVP.resolve($.ajax(/*your request to /service1 with all data and params, may use query-params!*/).then(data => {
return data; // extract the data you need, may transform the response, etc.
},
service2: Ember.RSVP.resolve($.ajax(/*your request to /service2 with all data and params, may use query-params!*/).then(data => {
return data; // extract the data you need, may transform the response, etc.
},
});
If you need the response of /service1 to fetch /service2 just do this in your model hook:
return Ember.RSVP.resolve($.ajax(/*/service1*/)).then(service1 => {
return Ember.RSVP.resolve($.ajax(/*/service2*/)).then(service2 => {
return {
service1,
service2
}; // this object will then be available as `model` on your controller
});
});
If this does not help you (and I really think this should fix your problems) please describe your Problem.

Backbone JS save functionality

I have written a rails back end to my project and when you save or create a new record,among the status 200 and a json representation of the post that was saved.
When I do the following in bacbone:
modelObject = new App.Models.Post();
modelObject.set({title: 'asdasdas', content: 'asdadasdasdasdasd'});
if (modelObject.isValid()){
modelObject.save().then( ... )
}
How do I get the post object that is returned? (assuming the post is successful).
On the rails side, when I do #post.save I also do render json: #post, status: 200 on a successful save in the create action so there is a json object coming back, I just dot know how to access it on the backbone side.
The backbone docs describe few ways how can you get response from server after calling save() function.
For example:
You need to specify error and success callbacks:
var model = new App.Models.Post();
model.set({title: 'some title', content: 'some content'});
var options = {
success: function(model, response){
console.log('success handler');
model.set({id: response.id});
},
error: function(model, xhr){
console.log('error handler');
}
};
Specify wait option to wait response from server before set model attributes:
options.wait = true;
Need to call save function with specified options:
if (model.isValid()) {
model.save({}, options);
}
The modelObject.save() call will return a promise object. You should chain a .done() call to that and pass it in a function, like this:
modelObject.save().done(function(e) {
// handle your response here
});
You could also handle a failure the same way using the .fail() function. Chain them together like this:
modelObject.save().done(function(e) {
// handle your response here
}).fail(function(e) {
// handle failure here
});
Here's another way to write the same code:
var promise = modelObject.save();
promise.done(function(e) {
// handle your response here
});
promise.fail(function(e) {
// handle failure here
});
There is also a .always() that you could chain to always be called:
var promise = modelObject.save();
promise.done(function(e) {
// handle your response here
});
promise.fail(function(e) {
// handle failure here
});
promise.always(function(e) {
// always call this on success or failure
});

backbonejs fetch returns twice (fail, then success)

I am calling my api which returns a task object via json (example return json below):
[{"pkTaskId":"96","fldName":"Change page to template","fldStatus":"Assigned","fldNotes":"http:\/\/williamsconcepts.com\/ci\/codeigniter\/libraries\/template\/reference.html\r\n\r\n111","fldDateDue":"0000-00-00 00:00:00","fldDateCompleted":"0000-00-00 00:00:00"},{"pkTaskId":"103","fldName":"fix list creation","fldStatus":"Assigned","fldNotes":"for some reason there is an SQL syntax error\r\n\r\nok","fldDateDue":"0000-00-00 00:00:00","fldDateCompleted":"0000-00-00 00:00:00"},{"pkTaskId":"104","fldName":"navicat db admin tool","fldStatus":"Assigned","fldNotes":"Try this out:\nhttp:\/\/www.navicat.com\/download\/download.html","fldDateDue":"0000-00-00 00:00:00","fldDateCompleted":"0000-00-00 00:00:00"},{"pkTaskId":"105","fldName":"Styling dropdowns","fldStatus":"Assigned","fldNotes":"Link:\nhttp:\/\/jqueryui.com\/demos\/autocomplete\/#combobox","fldDateDue":"0000-00-00 00:00:00","fldDateCompleted":"0000-00-00 00:00:00"},{"pkTaskId":"147","fldName":"api create task","fldStatus":"Assigned","fldNotes":"","fldDateDue":"0000-00-00 00:00:00","fldDateCompleted":"0000-00-00 00:00:00"}]
$(function(){
window.Task = Backbone.Model.extend({});
window.TaskList = Backbone.Collection.extend({
model: Task,
url: "http://localhost/tasker/index.php/api/tasks/username/lucasmp"
});
window.tasks = new TaskList();
window.AppView = Backbone.View.extend({
initialize: function() {
tasks.fetch({
success: function() {
console.log(tasks.toJSON());
}
});
}
});
window.App = new AppView;
});
$('#fetch').click(function(){
tasks.fetch({
success: function() {
alert("success");
console.log(tasks.toJSON());
},
error: alert("error")
});
});
I'm having an issue though with my fetch.click occurring twice; Once returns fetch error, then returns fetch success. What could be causing this to be fired twice?
Pls try this
error: function(){alert("error")}

Categories

Resources