c#,mvc,backbone, timer - javascript

I'm trying to create multiple timers. Any tutorials which can help me. The most difficult part is the html part and how to link my files a sample project would do me good.
Html5.Views.Timer = Backbone.View.extend({
el: 'div#timer',
initialize: function() {
timer = this.model;
this.render();
},
events: {
"clicked div#add_time": "update_timer"
}
render: function() {
$(this.el).append(HandlebarsTemplates['timer'](timer);
this.start_timer();
},
start_timer: function() {
clearTimeout(this.main_timer);
this.main_timer = setTimeout(function() {
if (this.countDownInstance) {
this.countDownInstance.clearRewriteCounter();
}
this.countDownInstance = new countDown(timed.length, 'main_timer');
}, timed_length*1000);
},
update_timer: function() {
timed.length = timed.length+30
this.start_timer();
}
});

I think there is a typo or you use timed_length or you use timed.length.. Also I think timed.length should returns an error at least there is a variable called timed in a global scope.
Also the line timer = this.model; is declaring a variable timer in a global scope.
Also the calls to timed_length maybe you want to change them to this.timed_length.
Summarizing.. I think there are a bunch of typos here.

Related

Hammer Js Not working with Backbone.js

I have problem in implementing touch events with backbone.js and hammer.js
I have tried implementing the touch in the conventional way i.e defining the touch events in "events" section.But it has not worked for me.
Please find my code below
define(['Backbone','underscore','Handlebars','Hammer'],function(Backbone,_,Handlebars,Hammer) {
//getting the type of device in a variable using "userAgent"
window.MOBILE = navigator.userAgent.match(/mobile/i);
var HeadderView = Backbone.View.extend(
{
el: 'body',
touchPrevents : false,
initialize: function()
{
this.el$ = $(this.el);
},
events: function() {//returning different functions based on the device
return MOBILE ?
{
'tap #headcontent': 'handleTap',
} :
{
'click #headcontent':'clickbackbone',
}
},
//declaring the corresponding functions
handleTap: function(){
alert("tap event");
},
clickbackbone:function(){
alert('backbone click');
},
render: function ()
{
//rendering the template and appending it to the page
var that = this;
require(['text!gaming/gameHeadder/headder.html'],function(HeaderTemplate){
var template = Handlebars.compile(HeaderTemplate);
var context = {title: "Tick Tack Toe", imageURL: "images/logo.jpg"}
var htmlTemplate = template(context);
that.el$.html( htmlTemplate);
});
},
});
return new HeadderView();
}
);
Can some one help me out and correct my code
This is not how Hammer works. Backbone knows nothing about HammerJS.
If you really want to use Backbone-style event delegation with Hammer, you might want to check out the backbone.hammer project.

Cloning $(this) in a javascript object?

I'm learning how to use objects to help organize my code and give it some structure but I've run into a problem. I don't understand how to set the $(this) from inside of one function to the $(this) of another function.
I'm researching call and apply but I can't seem to grasp how it works in this scenario.
cloneCard and clickCard is where I'm having the problem. I want to pass the $(this) that is referenced when I click the card to the cloneCard function.
Here is my code so far (updated to reflect the answer):
var Modal = {
init: function(config) {
this.config = config;
this.clickCard();
this.removeModal();
this.clickOutside();
this.createClose();
},
clickCard: function() {
$this = this;
this.config.boardOutput.on('click', '.card', function(event) {
$this.showOverlay();
$this.cloneCard.call($(this));
$this.createClose();
});
},
cloneCard: function() {
this.clone()
.replaceWith($('<div/>').html(this.html()))
.removeClass('card')
.addClass('modal')
.css("margin-top", $(window).scrollTop())
.prependTo('body');
},
showOverlay: function() {
this.config.overlay.show();
},
removeModal: function() {
$('.modal').remove();
$('.overlay').hide();
},
clickOutside: function() {
this.config.overlay.on('click', this.removeModal);
},
createClose: function() {
$('<span class="close">X</span>')
.prependTo('.modal')
.on('click', this.removeModal);
}
};
Modal.init({
boardOutput: $('#board-output'),
overlay: $('.overlay')
});
For what you need, calling self.cloneCard.call($(this)); instead of self.cloneCard($(this));
should work. What you're doing is, calling cloneCard passing it the element in which the the clickCard event occured.
If this doesn't work, i think we'll need more information to sovle your problem.

Old Backbone View Causing extra Event Triggers

OK, I've done some reading on this and I'm pretty sure I know what the problem relates to I Just don't know the best way to fix it. I've got the standard backbone router that sets me up with an item details view, then when I click on a button called "start" it creates a new view which takes me to a sort of a game that people can play with some buttons on the bottom that have "click" events attached. This second view is not called through the router but directly from the first view.
The problem is the second time someones goes back to the homescreen and does it again, this time there are two events attached to each button. The third time there are three events. Obviously the original views are still listening to these buttons. I've read about this and calling the Remove() method but is this what I need to do? If so where do I call remove? Relevant Code below:
1ST VIEW
window.GameDrillView = Backbone.View.extend({
initialize: function () {
this.render();
},
render: function () {
$(this.el).html(this.template(this.model.toJSON()));
return this;
},
events: {
"click .start" : "startGameDrill",
},
startGameDrill: function () {
var start = $('#start').val();.
var stop = $('#stop').val();.
var StartView = new GameDrillStartView({model: this.model, el: $('#content')[0], start: start, stop:stop});
}
});
START VIEW
window.GameDrillStartView = Backbone.View.extend({
// declare variables
initialize: function () {
this.render();
},
events: {
"click .nextstage" : "nextstage", // 2ND TIME THROUGH GETS CALLED TWICE
},
nextstage: function () {
// Do some stuff //
this.render(); //Re-render
},
render: function () {
// Do some variables stuff
this.$el.html(this.template(jQuery.extend(this.model.toJSON(), extended_options)));..
return this;
}
});
When changing view you need to call undelegateEvents() method from the Backbone.View. It disable listening all the elements events mentioned in events { } block. Also if you need to destroy old view you can call remove() method of the view which will call undelegateEvents() internally.
update (example from official site)
var Workspace = Backbone.Router.extend({
routes: {
"help": "help", // #help
"search/:query": "search", // #search/kiwis
"search/:query/p:page": "search" // #search/kiwis/p7
},
help: function() {
if (this.currentView)
this.currentView.undelegateEvents();
this.currentView = new HelpView();
},
search: function(query, page) {
if (this.currentView)
this.currentView.undelegateEvents();
this.currentView = new SearchView();
}
});
An option is to create only one instance of the view:
if(_.isUndefined(this.StartView))
this.StartView = new GameDrillStartView({model: this.model, el: $('#content')[0], start: start, stop:stop});
else
this.StartView.render();
In the render method of GameDrillStartView add the empty method
this.$el.html(this.template(jQuery.extend(this.model.toJSON(), extended_options)))
In this way you won't add more event listeners but you'll update the page everytime the user presses the button.
You can manage the life cycle of StartView in GameDrillView since it seems like a better place to do so.
Got same trouble. Messy solution:
var current_view = false;
var prev_view = false;
var AppRouter = Backbone.Router.extend({
routes: {
"events/:id": "viewEvent",
}
});
var app_router = new AppRouter;
app_router.on('route:viewEvent', function (event_id) {
var _event = new Event({id:event_id});
current_view = new EventView({
model: _event,
});
});
//Will be called after route:viewEvent
app_router.on('route', function () {
if(prev_view) {
prev_view.undelegateEvents();
}
prev_view = current_view;
});
Not sure, how to make it without having current_view and prev_view out of router scope.

jQuery click event not working while using "Module Pattern"

I'm an intermediate front-end JS developer and I'm trying the Module Pattern outlined by Chris Coyyer here.
But when I store a jQuery selector in the settings, I'm unable to use it to trigger a click event. See the below code with my comments... Any help is greatly appreciated!
var s,
TestWidget = {
settings: {
testButton: $("#testing")
},
init: function() {
s = this.settings;
this.bindUIActions();
},
bindUIActions: function() {
console.log(s.testButton); // This works: [context: document, selector: "#testing", constructor: function, init: function, selector: ""…]
//This doesn't work - why?????
s.testButton.click(function() {
//Why isn't this triggered?
alert('testButton clicked');
});
/*This works, obviously:
$('#testing').click(function() {
alert('testButton clicked');
});
*/
}
};
$(document).ready(function() {
TestWidget.init();
});
The problem is that you initialize $("#testing") before the DOM is ready, so this jQuery object is empty.
A simple solution is to put all your code in the ready callback.
Another one would be to replace
settings: {
testButton: $("#testing")
},
init: function() {
s = this.settings;
this.bindUIActions();
},
with
settings: {
},
init: function() {
s = this.settings;
s.testButton = $("#testing");
this.bindUIActions();
},
But it's hard to get why you use so much code for such a simple thing. You might be overusing the pattern here and it's not really clean as you have two global variables s and TestWidget when one would already be a lot.
Here's a slight variation of your code which would be, in my opinion, cleaner, while still using modules (IIFE variant) :
TestWidget = (function(){
var settings = {};
return {
init: function() {
settings.testButton = $("#testing");
this.bindUIActions();
},
bindUIActions: function() {
console.log(settings.testButton);
settings.testButton.click(function() {
alert('testButton clicked');
});
}
}
})();
$(document).ready(function() {
TestWidget.init();
});
settings is kept in the closure and doesn't leak in the global namespace. Note that even this version doesn't make sense if you don't do more with the module.

dojo.hitch() scope for window.setInterval()

I am trying to produce a blinking effect using dojo fadeIn/Out.
The following snippet of code is defined inside the declaration of a widget class:
_startHighlightEffect : function() {
var blinkInterval = 5000; //Scope here is that of the parent widget
window.setInterval ( function() {
dojo.fadeOut(
{
node: this._headerDiv.domNode,
onEnd: function() {
dojo.fadeIn({node: this._headerDiv.domNode},3000).play();
}
},3000).play();
}, blinkInterval);
},
_highlightEffect : function() {
this.func = dojo.hitch(this,this._startHighlightEffect);
this.func();
}
The problem I am facing is that it says,"this._headerDiv is undefined". On checking with firebug, the scope of this._headerDiv is Window instead of the parent widget.
Please help me understand what am I missing here.
What #jbabey describes will work, but in terms of dojo.hitch, you used it on the wrong function. You need to hitch the function that is passed into setInterval.
_startHighlightEffect : function() {
var blinkInterval = 5000; //Scope here is that of the parent widget
// hitch the function that will be executed by the setInterval call *********
window.setInterval (dojo.hitch(this, function() {
dojo.fadeOut(
{
node: this._headerDiv.domNode,
onEnd: dojo.hitch(this, function() {
dojo.fadeIn(
{node: this._headerDiv.domNode},3000).play();
})
},3000).play();
}, blinkInterval));
},
_highlightEffect : function() {
this._startHighlightEffect();
}
you can save the context when it is the context you want, and use it later:
_startHighlightEffect : function() {
var blinkInterval = 5000; //Scope here is that of the parent widget
var that = this; // save the scope
window.setInterval ( function() {
dojo.fadeOut(
{
node: that._headerDiv.domNode, // use the saved scope
onEnd: function() {
dojo.fadeIn({node: that._headerDiv.domNode},3000).play();
}
},3000).play();
}, blinkInterval);
}

Categories