Ajax queue Backbone js - ruby-on-rails

I am running Backbone js 0.9.2 on Rails 3.2.2,I have a page for adding cost rows.A cost have 3 TextFields: title, description and price.
I am saving each cost on blur.
model.save() gets called multiple times with very short intervals. Which issues one create(post) request then one update(put) request shortly there after. The problem I am experiencing is that PUT request sometimes reaches the server before the POST, the result being that model gets created and persisted twice(duplicates).
To save on blur is the requested behavior, so I need a way to queue up requests.
I have read something about Spine js, and that they solve it by some kind of queue. I've also looked in to this, but can't seem to figure this out.
It feels like this should be a common issue, working with "single-page-apps" but can't find anything about it.

You could override the save method and create a queue with a deferred object . For example,
var MDef = Backbone.Model.extend({
url: "/echo/json/?delay=3",
initialize: function() {
this.queue = $.Deferred();
this.queue.resolve();
},
save: function(attrs,options) {
var m = this;
console.log("set "+JSON.stringify(attrs));
// this.queue = this.queue.pipe with jquery<1.8
this.queue = this.queue.then(function() {
console.log("request "+JSON.stringify(attrs));
return Backbone.Model.prototype.save.call(m, attrs, options);
});
}
});
var m = new MDef();
m.save({title: "a title"});
m.save({description: "a description"});
m.save({price: "a price"});
And a Fiddle : http://jsfiddle.net/nikoshr/8nEUm/

User debounce from underscore.js.
Creates and returns a new debounced version of the passed function that will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked.
This way it will only fire once after the last blur event.

Related

Issue with mobile.loading and timing - JQuery Mobile

I am trying to show the loading animation during a function call that takes some time. The function call is searching a large array that is already loaded. After the search, matching items are inserted into a table. The table is cleared prior to starting the search.
The problem is the animation only displays during the brief moment when the page updates.
Here is my code:
var interval = setInterval(function ()
{
$.mobile.loading('show');
clearInterval(interval);
}, 1);
DoSearch(term, function ()
{
var interval = setInterval(function ()
{
$.mobile.loading('hide');
clearInterval(interval);
}, 1000);
});
//The search function looks like this (detail omitted for brevity):
function DoSearch(term)
{
$("table#tableICD tbody").html('');
// also tried:
/*$("table#tableICD tbody")
.html('')
.table()
.closest("table#tableICD")
.table("refresh")
.trigger("create");*/
var tr = '';
$.each(codes, function (key, value)
{
// determine which items match and add them as table rows to 'tr'
});
$("table#tableICD tbody")
.append(tr)
.closest("table#tableICD")
.table("refresh")
.trigger("create");
callback();
}
The search works properly and adds the rows to the table. I have two unexpected behaviors:
The table does not clear until the search is complete. I have tried adding .table("refresh").trigger("create") to the line where I set the tbody html to an empty string. This does not help. (see commented line in the code)
As I mentioned, the animation displays briefly while the screen is refreshing. (Notice I set the interval to 1000 in the second setInterval function just so I could even see it.)
The suggestions I have read so far are to use setInterval instead of straight calling $.mobile.loading, which I have done and placing the search in a function and using a callback, which I have also done.
Any ideas?
Let me give you a few suggestions; they will probably not solve all your issues but they may help you found a solution.
jQuery Mobile is buggy, and for some features, we will never know were they intended to work like that or are they just plain bugs
You can call $.mobile.loading('show') on its own only in pageshow jQuery Mobile event. In any other case, you need to do it in interval or timeout.
It is better to do it in timeout, mostly because you are using less code. Here an example I made several years ago: http://jsfiddle.net/Gajotres/Zr7Gf/
$(document).on('pagebeforecreate', '[data-role="page"]', function(){
setTimeout(function(){
$.mobile.loading('show');
},1);
});
$(document).on('pageshow', '[data-role="page"]', function(){
// You do not need timeout for pageshow. I'm using it so you can see loader is actualy working
setTimeout(function(){
$.mobile.loading('hide');
},300);
});
It's difficult to enhance any jQuery Markup in real time after a page was loaded. So my advice is to first generate new table content, then clean it, and then update markup using .table("refresh").
Do table refresh only once, never do it several times in the row. It is very resourced heavy method and it will last a very long time if you run it for every row
If you are searching on keypress in the input box then showing it in the table; that is the least efficient method in jQuery Mobile. jQM is that slow, it is much better to use listview component which is least resource extensive.

Knockout mapping is not updating my model

I'm having trouble with a knockout model that is not binding on a subscribed update. I have a C# MVC page that delivers a model to the template which is parsed to Json and delivered raw as part of a ViewModel assignment for ko.applyBindings. I have a subscription to an observable that calls a method to perform an update of the viewModel's data. Irrelevant stuff pulled out and renamed for example usage:
var myViewModel = function (data) {
var self = this;
self.CurrentPage = ko.observable();
self.SomeComplexArray= ko.observableArray([]);
self.Pager().CurrentPage.subscribe(function (newPage) {
self.UpdateMyViewModel(newPage);
});
self.UpdateMyViewModel= function (newPage) {
var postData = { PageNumber: newPage };
$.post('/Article/GetMyModelSearchByPage', postData, function (data) {
ko.mapping.fromJS(data, {}, self);;
});
};
When I perform logging, I can see all of the data, and it all looks correct. The same method is used to produce both the initial model and the updated model. I've used this technique on other pages and it worked flawlessly each time. In this case however, I'm looking for it to bind/update SomeComplexArray, and that's just not happening. If I attempt to do it manually, I don't get a proper bind on the array I get blank. I'm wondering if there is something obvious that I'm doing wrong that I'm just flat out missing.
Edit: I don't know that ko.mapping can be pointed to as the culprit. Standard model changes are also not affecting the interface. Here is something that is not working in a bound sense. I have a p element with visible bound to the length of the array and a div element with a click bound to a function that pops items off of SomeComplexArray. I can see in the console log that it is performing its function (and subsequent clicks result in 'undefined' not having that function). However, the p element never displays. The initial array has only 2 items so a single click empties it:
<p data-bind="visible: SomeComplexArray().length === 0">nothing found</p>
<div data-bind="click: function() { UpdateArray(); }">try it manually</div>
-- in js model
self.UpdateArray = function () {
console.log(self.SomeComplexArray());
console.log(self.SomeComplexArray().pop());
console.log(self.SomeComplexArray());
console.log(self.SomeComplexArray().pop());
console.log(self.SomeComplexArray());
});
Edit 2: from the comment #Matt Burland, I've modified how the pop is called and the manual method now works to modify the elements dynamically. However, the ko.mapping is still not functioning as I would expect. In a test, I did a console.log of a specific row before calling ko.mapping and after. No change was made to the observableArray.
I created a test of your knockout situation in JSFiddle.
You have to call your array function without paranthesis. I tested this part:
self.UpdateArray = function () {
self.SomeComplexArray.pop();
};
It seems to be working on JSFiddle side.
I'm not really sure why, but it would seem that ko.mapping is having difficulty remapping the viewmodel at all. Since none of the fields are being mapped into self my assumption is that there is an exception occurring somewhere that ko.mapping is simply swallowing or it is not being reported for some other reason. Given that I could manually manipulate the array with a helpful tip from #MattBurland, I decided to backtrack a bit and update only the elements that needed to change directly on the data load. I ended up creating an Init function for my viewModel and using ko.mapping to populate the items directly there:
self.Init = function (jsonData) {
self.CurrentPage(0);
self.Items(ko.mapping.fromJS(jsonData.Items)());
self.TotalItems(jsonData.TotalItems);
// More stuff below here not relevant to question
}
The primary difference here is that the ko.mapping.fromJS result needed to be called as a function before the observableArray would recognize it as such. Given that this worked and that my controller would be providing an identical object back during the AJAX request, it was almost copy/past:
self.UpdateMyViewModel= function (newPage) {
var postData = { PageNumber: newPage };
$.post('/Article/GetMyModelSearchByPage', postData, function (data) {
self.Items(ko.mapping.fromJS(JSON.parse(data).Items)());
});
};
This is probably not ideal for most situations, but since there is not a large manipulation of the viewModel occurring during the update this provides a working solution. I would still like to know why ko.mapping would not remap the viewModel at the top level, but in retrospect it probably would have been a disaster anyway since there was "modified" data in the viewModel that the server would have had to replace. This solution is quick and simple enough.

cancelling 1 interval on pageChange

I have 2 pages that require a function to be called every minute so I did this using setInterval(). However whenever I navigate to the page a new interval is created and it eventually bogs down the site. Is there a way to cancel an interval whenever I navigate away from a page?
var pollinginterval = 60000;
$('#HomeViewPage_MyLocation').live('pagebeforeshow', function(toPage, fromPage){
GetUsersByLocation();
setInterval(function() {
GetUsersByLocation();
}, pollinginterval);
});
$('#HomeViewPage_ColleagueLocation').live('pageshow', function(toPage, fromPage){
GetAllUsersByTeam();
GetAvailableTeams();
setInterval(function() {
GetAllUsersByTeam();
GetAvailableTeams();
}, pollinginterval);
});
Do you mean when refreshing the browser page? Then you can stop it by listenting for unload:
var runMyFunction = function() {
// clear interval
};
window.onunload = runMyFunction();
If not, you can still clear the interval on your internal page change.
This is because jQM has a problem with multiple events. Ok it is not a problem, you must understand, in your case, each time you access your page same event is applied again.
You can do 2 things to solve this problem:
Instead of live use bind/unbind and on/off to unbind event before binding it again to same element after each pagebeforeshow/pageshow. This is not that good approach.
Example for click event:
$('#elementID').unbind();
$('#elementID').bind('click', function(e) {
});
Correct one would be to use Event filter to check if event is already bound. It can be found here: http://www.codenothing.com/archives/2009/event-filter/
Example for click event:
$('#elementID:Event(click)').each(function(){
});

"Too Much Recursion" Problem

I'm helping a company develop a website that utilizes jquery but I have noticed that the site slows to a complete halt with a jquery "Too Much Recursion" error. The company really needs to get this resolved but retain the slideshow capabilities as they are right now. Here is the code in question:
<script type="text/javascript">
var $testimonialCont;
var $slideshowContainer;
$(document).ready(function(){
$slideshowContainer = $('.slideshowContainer');
var inititalSlideshowDelay = setTimeout(cycle_slideshow_image, 4000);
$testimonialCont = $('.testimonialContainer');
$('.testimonialBubble').hide();
$('.testimonialBubble').removeClass('hide');
cycle_top_bubble()
var initialTestimonialDelay = setTimeout(cycle_top_bubble, 3000);
});
function cycle_slideshow_image(){
//This code cycles the slideshow caption headings and body text
$('h1.slideshowCaptionHeading:last').fadeOut(1500, function(){
$(this).prependTo('.captionHeaderArea');
$(this).show(1);
var delay = setTimeout(cycle_slideshow_image, 4000);
});
$('p.slideshowCaptionBody:last').fadeOut(1500, function(){
$(this).prependTo('.captionBodyArea');
$(this).show(1);
var delay = setTimeout(cycle_slideshow_image, 4000);
});
$('img.slideshowSlide:last').fadeOut(1500, function(){
$(this).prependTo($slideshowContainer);
$(this).show(1);
var delay = setTimeout(cycle_slideshow_image, 4000);
});
}
function cycle_top_bubble(){
$('.testimonialBubble:last').prependTo($testimonialCont).fadeIn(1500, function(){
var $this = $(this);
var thisTimer = setTimeout(function(){
$this.fadeOut(1500, function(){
var thisDelay = setTimeout(cycle_top_bubble, 3000);
})
}, 5000);
});
}
</script>
Here is the site's address: http://dbunderdevelopment.com/CRR/
If anyone has any suggestions, I would greatly appreciate it.
P.S. I did post this question before as an unregistered user and I sincerely apologize in advance for that. I can't seem to find the post in order to delete but, rest assured, it will not happen again. I know how bad repostings are on forums.
To me it looks like cycle_slideshow_image calls itself three times each time it is called... change it to this:
function cycle_slideshow_image(){
//This code cycles the slideshow caption headings and body text
$('h1.slideshowCaptionHeading:last').fadeOut(1500, function(){
$(this).prependTo('.captionHeaderArea');
$(this).show(1);
});
$('p.slideshowCaptionBody:last').fadeOut(1500, function(){
$(this).prependTo('.captionBodyArea');
$(this).show(1);
});
$('img.slideshowSlide:last').fadeOut(1500, function(){
$(this).prependTo($slideshowContainer);
$(this).show(1);
var delay = setTimeout(cycle_slideshow_image, 4000);
});
}
Also, cycle_top_bubble is being called twice initially, so it's running in two loops. remove this line:
var initialTestimonialDelay = setTimeout(cycle_top_bubble, 3000);
Another thing to consider is that when your page becomes an inactive tab in the browser, the timeouts are clamped to 1000ms (ref) so the animation may build up if you have the timeouts too short, which you don't, but it's something to keep in mind.
So you need to think about how recursion works, when you recurse in those set timeout functions you create a new scope inside the recursed function, Adding everything onto the stack without popping off the last function.
If you look at this as it is a block of memory but you never recurse which is the returning back up you continue to flood memory with more and more objects until its full. How you can solve this is pretty easy.
First recursion is the wrong approach for something that never completes, I explained why above. The recursion needs to be changed. The solution I would use is have a callback on the setTimeout but move your setTimeouts outside the scope of the calling function. This should help with the memory problem.
Other suggestions is to use a real slideshow plugin that someone else wrote... I know this may be frowned upon but why recreate the wheel when it has been done 1000 times. I recommend jQuery Cycle it is extremely fast and customizable.
Good luck!

jQuery UI Sortable: Revert changes if update callback makes an AJAX call that fails?

I am using the sortable widget to re-order a list of items. After an item is dragged to a new location, I kick off an AJAX form post to the server to save the new order. How can I undo the sort (e.g. return the drag item to its original position in the list) if I receive an error message from the server?
Basically, I only want the re-order to "stick" if the server confirms that the changes were saved.
Try the following:
$(this).sortable('cancel');
I just encountered this same issue, and for the sake of a complete answer, I wanted to share my solution to this problem:
$('.list').sortable({
items:'.list:not(.loading)',
start: function(event,ui) {
var element = $(ui.item[0]);
element.data('lastParent', element.parent());
},
update: function(event,ui) {
var element = $(ui.item[0]);
if (element.hasClass('loading')) return;
element.addClass('loading');
$.ajax({
url:'/ajax',
context:element,
complete:function(xhr,status) {
$(this).removeClass('loading');
if (xhr.status != 200) {
$($(this).data('lastParent')).append(this);
}
},
});
}
});
You'll need to modify it to suit your codebase, but this is a completely multithread safe solution that works very well for me.
I'm pretty sure that sortable doesn't have any undo-last-drop function -- but it's a great idea!
In the mean time, though, I think your best bet is to write some sort of start that stores the ordering, and then on failure call a revert function. I.e. something like this:
$("list-container").sortable({
start: function () {
/* stash current order of sorted elements in an array */
},
update: function () {
/* ajax call; on failure, re-order based on the stashed order */
}
});
Would love to know if others have a better answer, though.

Resources