Category Archives: backbone

Replace confirm with Bootstrap modal and Backbone view

We all hate ugly confirms but now you can use a nice backbone view and bootstrap modal to bug your users and act on btn click.

Modal:

<div class="modal fade" id="confirm-modal">
 <div class="modal-dialog">
 <div class="modal-content">
 <div class="modal-header">
 <span id="header-text"></span><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
 <h4 class="modal-title">Are You Sure?</h4>
 </div>
 <div class="modal-body">
 </div>
 <div class="modal-footer">
 <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary btn-ok" data-dismiss="modal">OK</button>
 </div>
 </div><!-- /.modal-content -->
 </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

Backbone View:

App.Views.ConfirmModalClass = Backbone.View.extend({
   el: "#confirm-modal",
   events: {
    "click .btn-ok": "runCallBack"
   },
   initialize: function(args){
	   this.$el.find(".modal-body").html("<p>"+args.body+"</p>");
	   this.cb = args.cb;
   },
   render: function(){
     this.$el.modal("show");
  },
  close: function(){
     this.$el.modal("close");
  },
  runCallBack: function(){
       this.cb();
  }
});

Usage (from inside another view):

var that = this;
	   var confirmModal = new App.Views.ConfirmModalClass({
	      cb: function(){
				//use that to run functions for this view
	      },
		  body: "BODY"
	   });
	    confirmModal.render();
Advertisements
Tagged , ,

Capture Current Location inside of a Backbone Model

Here is how I take the lat and lng from the browser and turn it into a Backbone Model with a function to figure out haversine

var CurrentLocationModel = Backbone.Model.extend({
   initialize: function(){
    this.getLocation();
  },
  getLocation: function(){
        var that = this;
		if (navigator.geolocation){	
			navigator.geolocation.getCurrentPosition(function(position){
				that.set("lat",position.coords.latitude);
				that.set("lng",position.coords.longitude);
			});
		}else{
		    that.set("lat",0);
			that.set("lng",0);
		}
   },
   getDistance: function(lat,lng){
        //see http://stackoverflow.com/questions/14560999/using-the-haversine-formula-in-javascript
		var that = this;
		var R = 6371; // km 
		console.log(that.get("lat"));
		//has a problem with the .toRad() method below.
		var x1 = that.get("lat")-lat;
		var dLat = x1.toRad();  
		var x2 = that.get("lng")-lng;
		var dLon = x2.toRad();  
		var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
					Math.cos(lat.toRad()) * Math.cos(that.get("lat").toRad()) * 
					Math.sin(dLon/2) * Math.sin(dLon/2);  
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
		var dist = R * c;
        return(dist);		
   }
  
});
Tagged , ,