Backbone + JQuery Mobile + RequireJS - jquery-mobile

I am having a big proglem with RequireJS. This configuration works randomly. I dont know why, once it works and once it doesn't:
requirejs.config({
baseUrl: 'js',
urlArgs: "bust=" + (new Date()).getTime(),
paths: {
jquery: 'libs/jquery/jquery-1.10.2.min',
underscore: 'libs/underscore/underscore-min',
backbone: 'libs/backbone/backbone-min',
marionette: 'libs/marionette/backbone.marionette',
cordova: 'libs/cordova/cordova-1.9.0',
jquerym: 'libs/jquery-mobile/jquery.mobile-1.4.0'
},
shim: {
'jquery': {
deps: []
},
'jquerym': {
deps: ['jquery'],
exports: 'jquery'
},
'underscore': {
deps: [],
exports: "_"
},
'backbone': {
deps: ['jquery', 'underscore'],
exports: 'Backbone'
},
'marionette': {
deps: ['jquery', 'underscore', 'backbone']
}
},
priority: ['jquery', 'jquerym']
});
require(['app', 'jquery', 'jquerym'], function (App) {
$(document).bind("mobileinit", function () {
$.mobile.ajaxEnabled = false;
$.mobile.linkBindingEnabled = false;
$.mobile.hashListeningEnabled = false;
$.mobile.pushStateEnabled = false;
// Remove page from DOM when it's being replaced
$('div[data-role="page"]').live('pagehide', function (event, ui) {
$(event.currentTarget).remove();
});
});
console.log('jQuery version ' + $().jquery + ' installed');
App.initialize();
});

The Mobile-Init-Event has to be bound before jQuery Mobile is loaded for it to be triggered correctly.
Try using something like this:
require(["jquery"], function( $ ){
$( document ).one( "mobileinit", function() {
//Set your configuration and event binding
$.mobile.ajaxEnabled = false;
$.mobile.linkBindingEnabled = false;
$.mobile.hashListeningEnabled = false;
$.mobile.pushStateEnabled = false;
// Remove page from DOM when it's being replaced
$('div[data-role="page"]').live('pagehide', function (event, ui) {
$(event.currentTarget).remove();
});
});
require( [ "App", "jquerym" ], function( App, jqm ) {
/* Do Stuff with jqm here if you want like jqm.initializePage() if turned off */
App.initialize();
});
});

Related

Why does using requirejs 2 stop my backbone / jQuery mobile app working?

I have a very simple proof of concept app built with jQuery Mobile, Backbone.js, and require.js.
I am using Backbone's router, and I have jQuery Mobile's routing disabled. It works perfectly.
I am using require.js 1.04. However: when I use requirejs 2.1.14, then I can't seem to disable jQuery Mobile's routing, and hence Backbone's routing stops working. Can't figure it out.
The following code works if I remove jQuery mobile, but stops working if I put jQuery mobile back in. Similarly, it will work with Require.js 1.0.4, but not with require.js 2.1.14:
index.html:
<html>
<body>
Click Here
<script data-main="main" src="require.js"></script>
</body>
</html>
main.js
require.config({
paths : {
backbone : 'libraries/backbone/backbone',
underscore : 'libraries/underscore/underscore',
jquery : 'libraries/jquery/jquery-1.7.1',
jqm : 'libraries/jquery.mobile/jquery.mobile',
router: 'router'
},
shim: {
jqm: {
exports: 'jqm',
deps: ['jquery']
},
underscore: {
exports: 'underscore'
},
backbone: {
exports: 'backbone',
deps: ['jquery', 'underscore']
}
}
});
require(
['jquery', 'jqm', 'underscore', 'backbone', 'router'],
function ($, $$, underscore, Backbone, router) {
$.mobile.ajaxEnabled = false;
$.mobile.linkBindingEnabled = false;
$.mobile.hashListeningEnabled = false;
$.mobile.pushStateEnabled = false;
$.mobile.changePage.defaults.changeHash = false;
router.init();
});
router.js
define(['jquery', 'jqm', 'underscore', 'backbone'],
function($, $$, _, Backbone) {
var init = function () {
$.mobile.ajaxEnabled = false;
$.mobile.linkBindingEnabled = false;
$.mobile.hashListeningEnabled = false;
$.mobile.pushStateEnabled = false;
$.mobile.changePage.defaults.changeHash = false;
var AppRouter = Backbone.Router.extend({
routes: {
"posts/:id" : "getSomePost",
"*action": "defaultRoute"
},
getSomePost: function(id) {
alert( "Get post number " + id );
},
defaultRoute: function( actions ){
console.log('Action: ' + actions );
}
});
// Instantiate the backbone router
var app_router = new AppRouter();
// Start Backbone history
Backbone.history.start();
};
return { init : init };
});
This problem is seriously baking my noodle!!
When I load up the app, I see a link saying "Click here". When the app uses requirejs-1.0.4 (or without jquery mobile) it works, I get an alert saying "get post number 1", and the URL looks like:
http://myapp.dev/src/#posts/1
but when using requirejs-2.1.14 and jQuery Mobile, I the URL quickly changes to this:
http://myapp.dev/src/posts/1
and nothing happens.
Help!
I finally found the answer to this problem. The issue is the timing of jQuery Mobile configuration. According to the jQuery Mobile docs:
Because the mobileinit event is triggered immediately, you'll need to
bind your event handler before jQuery Mobile is loaded
So I rewrote main.js like so:
require.config({
paths : {
backbone : 'libraries/backbone/backbone',
underscore : 'libraries/underscore/underscore',
jquery : 'libraries/jquery/jquery-1.7.1',
jqmconfig : 'jquerymobile.config',
jqm : 'libraries/jquery.mobile/jquery.mobile',
router: 'router'
},
shim: {
jqm: {
exports: 'jqm',
deps: ['jquery', 'jqmconfig']
},
underscore: {
exports: 'underscore'
},
backbone: {
exports: 'backbone',
deps: ['jquery', 'jqm', 'underscore']
}
}
});
require(
['jquery', 'backbone', 'jqmconfig', 'jqm', 'router'],
function ($, Backbone, jqmconfig, $$, router) {
router.init();
});
And added a new file called jquerymobile.config.js:
define(['jquery'], function ($) {
$(document).on('mobileinit', function () {
// Prevents all anchor click handling
$.mobile.linkBindingEnabled = false
// Disabling this will prevent jQuery Mobile from handling hash changes
$.mobile.hashListeningEnabled = false
$.mobile.ajaxEnabled = false;
$.mobile.pushStateEnabled = false;
});
});
This code fires after jQuery has loaded, but BEFORE jQuery Mobile has loaded, which is the key!
For reference, this is the blog post that helped me figure it out:
http://www.justinmccandless.com/blog/Yeoman%2C+Requirejs%2C+jQuery+Mobile%2C+Backbone%2C+and+a+Lot+of+Config+Problems

How to use Jquery autocomplete with the backend couchDb

So far I've used Jquery autocomplete for backend php. But I want to use jquery auto complete to fetch records from couchdb. Can anyone please help me.
Or is there any other way to achieve autocomplete with couchDB
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$("#search_name").autocomplete({
source: function( request, response ) {
$.couch.db("db1").view("Views/testPatients", {
success: function(data) {
response(data.rows);
},
error: function(status) {
console.log(status);
},
key: request.term
});
},
minLength: 3,
focus: function(event, ui) {
console.log(ui.item.key);
$("#search_name").val(ui.item.key);
return false;
},
select: function( event, ui ) {
$("#search_name").val(ui.item.key);
return false;
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
}).
data("uiAutocomplete")._renderItem = function(ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.key + "</a>")
.appendTo(ul);
};

Datepicker jqueryui not works with require.js and backbone.js

Jquery ui datepicker not works on click on input.
main.js
require.config({
baseUrl: "js",
paths: {
html5shiv: "libs/html5shiv",
jquery: "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min",
jqueryui: "http://code.jquery.com/ui/1.10.3/jquery-ui",
tablesorter: "libs/jquery.tablesorter.min",
script: "script",
underscore: "libs/underscore.min",
backbone: "libs/backbone.min",
utils: "utils",
collectorModel: "models/collectorModel",
collectorCollection: "collections/collectorCollection",
tollectorRouter: "routers/tollectorRouter",
edit: "views/collector/tollector_edit",
index: "views/collector/collector_index",
neww: "views/collector/collector_new",
row: "views/collector/collector_row",
show: "views/collector/collector_show",
'templates': 'templates'
},
shim: {
jqueryui: {
deps: ["jquery"],
exports: "Jqueryui"
},
tablesorter: {
deps: ["jquery"],
exports: "TableSorter"
},
script: {
deps: ["jquery", "jqueryui", "tablesorter"],
exports: "Script"
},
jqueryui: {
deps: ["jquery"]
},
underscore: {
exports: "_"
},
backbone: {
deps: ["underscore", "jquery"],
exports: "Backbone"
}
}
});
require(["backbone", "underscore", "collectorCollection", "collectorRouter", "script"],
function (Backbone, _, CollectorCollection, CollectorRouter) {
var collectors = new CollectorCollection();
var router = new CollectorRouter({collectors: collectors});
Backbone.history.start();
});
Template: collector_edit.html
input type="text" class="inputs dateInput" name="endDate" placeholder="End date" value="<%= endDate %>
scripts.js
$(document).ready(function () {
$(".dateInput").datepicker({dateFormat: "dd/mm/yy"});
});
it worked before using backbone and RequireJS
When using requireJS your dependencies do not exist in the global scope anymore but only inside modulde that requires them. Try changing your script JS to:
define(['jqueryui'], function( jqueryui ) {
$(document).ready(function () {
$(".dateInput").datepicker({dateFormat: "dd/mm/yy"});
});
})

Uploadify - How to capture the newly created ID for scriptdata?

I have solved the problem myself now, below is the solution:
No problem any more. I am only writing this to get my text validated.
<script type="text/javascript">
/***************************************************/
/* THIS VARIABLE IS USED TO TRANSPORT THE NEW ID. */
var assignmentId;
/***************************************************/
$("#btnSave").click
(
function () {
var inputData = $("form").serialize();
var url = $("form").attr("action");
$.post(url, inputData, function (data) {
/********************************************************/
/* NOW UPLOADIFY GETS THE NEW ID!! */
assignmentId = data.AssignmentID;
alert(assignmentId.toString());
$('#fileuploader').uploadifySettings("scriptData", { 'currentValue': assignmentId });
/********************************************************/
$('#fileuploader').uploadifyUpload();
});
}
);
$("#fileuploader").uploadify({
'uploader': '#Url.Content("/Scripts/uploadify/uploadify.swf")',
'cancelImg': '/Scripts/uploadify/cancel.png',
'buttonText': 'Browse For File',
'script': '#Url.Action("Upload")',
'folder': '/uploads',
'scriptData': { 'currentValue': assignmentId },
'onAllComplete': function (event, data) { window.location = "/Assignment/" + assignmentId; },
'onError': function (a, b, c, d) {
},
'onSelectOnce': function (event, data) { noFilesToUpload = false; },
'fileDesc': 'Media Files',
'fileExt': '*.jpg;*.jpeg;',
'sizeLimit': 27000000,
'multi': false,
'auto': false
});
</script>
Thank you!
I have solved the problem myself now, below is the solution:
No problem any more. I am only writing this to get my text validated.
<script type="text/javascript">
/***************************************************/
/* THIS VARIABLE IS USED TO TRANSPORT THE NEW ID. */
var assignmentId;
/***************************************************/
$("#btnSave").click
(
function () {
var inputData = $("form").serialize();
var url = $("form").attr("action");
$.post(url, inputData, function (data) {
/********************************************************/
/* NOW UPLOADIFY GETS THE NEW ID!! */
assignmentId = data.AssignmentID;
alert(assignmentId.toString());
$('#fileuploader').uploadifySettings("scriptData", { 'currentValue': assignmentId });
/********************************************************/
$('#fileuploader').uploadifyUpload();
});
}
);
$("#fileuploader").uploadify({
'uploader': '#Url.Content("/Scripts/uploadify/uploadify.swf")',
'cancelImg': '/Scripts/uploadify/cancel.png',
'buttonText': 'Browse For File',
'script': '#Url.Action("Upload")',
'folder': '/uploads',
'scriptData': { 'currentValue': assignmentId },
'onAllComplete': function (event, data) { window.location = "/Assignment/" + assignmentId; },
'onError': function (a, b, c, d) {
},
'onSelectOnce': function (event, data) { noFilesToUpload = false; },
'fileDesc': 'Media Files',
'fileExt': '*.jpg;*.jpeg;',
'sizeLimit': 27000000,
'multi': false,
'auto': false
});
</script>

twice occuring drop events from jquery ui

I am using jquery ui 1.7.2 alongwith jquery 1.3.2
The following script is causing drop event to be triggered twice.. I tried a lot of time but not able to figure out why?
any suggestions to fix this code
$("document").ready(function () {
$(".draggable").draggable({
revert: "invalid",
helper: "clone",
connectToSortable: ".column"
});
$(".column").droppable({
accept: ".draggable",
drop: function (event, ui) {
debugger;
var ordinalNo = 1;
$(".column .contentObject").each(function () {
ordinalNo = ordinalNo + 1;
});
var objectId = guidGenerator() + '_' + ordinalNo;
var objectType;
var contentObjContent = "<div id=\"" + objectId + "\" ><h2>[<span class=\"ordinal\"></span>] ";
if (event.srcElement.id === "tableobj") {
objectType = tableSource;
}
else if (event.srcElement.id === "chartobj") {
objectType = chartSource;
}
else if (event.srcElement.id === "textobj") {
objectType = textSource;
}
$.ajax({
url: "/ContentBuilder/ContentObject",
data: {
viewObjectId: objectId,
contentObjectId: null,
contentObjectTypeId: objectType,
contentObjSourceId: null,
ordinal: ordinalNo
},
type: "POST",
success: function (data) {
contentObjContent = data;
}
});
}
});
$(".column").sortable({
connectWith: '.column',
handle: 'h2',
cursor: 'move',
placeholder: 'placeholder',
forcePlaceholderSize: true,
opacity: 0.4,
update: function (event, ui) {
changeOrdinal();
if (event.srcElement.id.length <= 0) {
updateObjectOrdinals();
}
}
}).disableSelection();
$(".tablecolumn").sortable({
connectWith: '.tablecolumn',
handle: 'h2',
cursor: 'move',
placeholder: 'placeholder',
forcePlaceholderSize: true,
opacity: 0.4,
update: function (event, ui) {
changeColumnOrdinal();
}
}).disableSelection();
});
becouse you use dropable AND sortable on the same selector $(".column"). I think both triggering a drop.

Resources