My app's index page is at http://cms/admin (I'm on localhost). On the index page there is only one a element:
deneme
When i click on the link it goes to /cms/admin/test
I want to use BackboneJS's routing mechanism to convert my app to ajax friendly app but i can't do it until now. Here is my JS code:
$(function() {
var AppRouter = Backbone.Router.extend({
routes: {
"test": "defaultRoute"
},
defaultRoute: function() {
console.log('its here');
}
});
var appRouter = new AppRouter();
Backbone.history.start({
pushState: true,
slient: true,
root: '/admin/'
});
});
When i run the page and click the link, it doesn't log anything to console and browser follows the link. After page loads, it logs "its here" message.
I already tried it without the root param, "/admin/test" instead of "test". i tried every combination of: "test", "/test", "test/", "/admin/test", "admin/test" etc..
Thanks.
You have to override the default behavior of the link.
You have to move between pages explicitly calling appRouter.navigate("test", {trigger: true});. So try to capture the click event over your link within a View.events, prevent the default behavior of the link and call appRouter.navigate()
Update
Also you can do it this in a batch:
$("a.bb_link").each( function( index, link ){
$(link).click( function( event ){
event.preventDefault();
appRouter.navigate( $(this).attr( "href" ), {trigger: true} );
});
});
Every link with class bb_link will be using the Backbone.Router.
Try setting your anchor tag as follows:
deneme
Note the hash (#)
Related
I am using Iron Router to launch Bootstrap modals from their specific URL in a Meteor project and I want to be able to use the browser back and forward buttons to navigate through them.
The problem:
Iron Router doesn't fire on the first time the browser's back button is clicked, after that it works fine!
My code:
I simplified the code a little bit but this is how I set the URL when a modal opens or closes(this works).
Template.main.events({
// modal closed -> URL to "/"
'click.dismiss.bs.modal': function () {
if(window.location.pathname != "/"){
// error prevention:
// click.dismiss.bs.modal also fires when user opens a modal
window.history.pushState("", "", "/");
}
},
// modal opened -> URL to "/u/username"
'click *[data-target="#infoModal"]': function () {
window.history.pushState("", "", "/u/" + username);
}
});
This is my router.js code, also a bit simplified. The console logs do not return the first time the browser's back button is pressed.
Router.route('/u/:username', {
name: 'u.show',
waitOn: function () {
return Meteor.subscribe('users');
},
action: function () {
console.log("Iron Router is trying to open #infoModal");
$('#infoModal').modal('show');
}
});
Router.route('/', {
name: 'home.show',
waitOn: function () {
return Meteor.subscribe('users');
},
action: function () {
console.log("Iron Router is trying to close all modals");
$('.modal').modal('hide');
}
});
I never worked with Iron Router before so I don't really know what I am doing wrong here, any help is much appreciated!
I think you need to use Router.go rather than manipulating browser history yourself. That way the library can "do the right thing" for its internal bookkeeping.
Template.MyButton.events({
'click #clickme': function () {
Router.go('/one');
}
});
You should also implement your route check using iron-router's built in facilities to make your life a little easier:
if(Router.current().route.getName() != 'home.show') {
Router.go('home.show');
}
That way if you ever change the URL (like putting the whole app under a subpath) then this code doesn't also have to be changed.
I am experiencing a strange error when I run my code. I am using an application with Backbone.js and RequireJS. The problem arises when there is an error in the code (any), seems that a backbone or jquery redirect to the url existing adding a question mark ? at the end of the page name:
URL before the error: http://localhost/home#users
URL after the error : http://localhost/home?#users
This causes the page to refresh. Anyone know why this behavior?
This is my code:
var myView = Backbone.View.extend({
events: {
'click button#lookUp':'lookUp'
},
lookUp: function(){
//Force error to show the error calling a function does not exist
this.triggerSomeError();
}
});
Router:
var navigate = function(url) {
appRouter.navigate(url, {
trigger: true
});
}
var initialize = function(){
appRouter = new AppRouter;
Backbone.history.start();
}
Html:
<button class="alinear-btn btn btn-primary" id="lookUp">Imprimir</button>
Chrome developer console:
This is a pretty common error that we've run into. You need to change your code to the following:
var myView = Backbone.View.extend({
events: {
'click button#lookUp':'lookUp'
},
lookUp: function(event) {
event.preventDefault();
//Force error to show the error calling a function does not exist
this.triggerSomeError();
}
});
By default an event object is passed to a function called from the events collection, and you need to use this to prevent the default behavior. You can name the parameter whatever. I just typically call it event to be explicit.
What you are actually suppressing here is the default behavior of that button in the browser, which is to do a form submit. When you do a form submit in the browser it tries to take everything that's in the form and append it on to the url as query parameters. In this case the button is not in any form and so it's basically appending nothing and just putting the question mark for the query parameters.
The reason you got down votes and the reason you're getting an error is because you didn't create a method in your view called triggerSomeError() so of course you're going to get an error on that. However that's completely independent and has nothing to do with what's going on with your url path.
I have a polymer element that loads dynamically with the constructor value that is load from api in jade. example:
ink(rel="import", href="/bower_components/polymer/polymer.html")
link(rel="import", href="/bower_components/core-ajax/core-ajax.html")
polymer-element(name='my-element', constructor='MyElement')
template
a(id='send', on-click='{{fileUpload}}')
form(id='filePost', action='', method='POST', accept-charset='utf-8', enctype='multipart/form-data')
input(id='fileinput', name='file', type='file')
script.
Polymer({
ready: function(){
//do something
},
launch:function(){
// prepare polymer element
},
fileUpload:function(){
// create XHR request and post file and on complete event exit to home view
},
exitUploader:function(){
history.pushState(null, null, '/home');
this.fire('goUrl');
this.remove();
},
});
ok so this works fine, on its own... although I have a basic app router that calls the file upload and navigation to the site. that goes something like this:
link(rel='import', href='/bower_components/polymer/polymer.html')
link(rel='import', href='/polymer/my-element') //api that returns jade to rendered html
polymer-element(name='router', attributes='attributes')
template
div(class='container', id='appView')
script.
(function(){
var routerView = document.querySelector('router')
//listen for 'navigate event' and render view
addEventListener('goUrl',function(e){
routerView.navigation(e);
});
Polymer({
ready:function(){
//do something
},
launch:function(){
// prepare polymer element
},
navigation: function(){
var self = this;
event.preventDefault();
event.stopPropagation();
this.location = window.location.pathname;
switch(true){
case(self.location == '/maker'):
var maker = new MyElement();
maker.launch();
this.$.appView.firstChild.remove();
this.$.appView.appendChild(maker);
break;
case(self.location == '/anotherlocation'):
var anyOtherElement = newPolymerElement();
this.$.appView.firstChild.remove();
this.$.appView.appendChild(anyOtherElement);
break;
}
},
});
})();
ok, so this works as well, my problem begins when i remove and re-render a new 'my-element' instance. when i upload such form it uploads an array of files pertinent to the history of files uploaded in previous visits. I was sure it had to do with removing the element properly from the dom on polymer, tried resetting the form on each time viewed the element. no dice. I need help! hahaha
thanks in advance
I'm pretty sure the issue is here:
var routerView = document.querySelector('router')
//listen for 'navigate event' and render view
addEventListener('goUrl',function(e){
routerView.navigation(e);
});
You're adding a listener outside of the lifecycle hooks, and not removing the listener when the element is removed from the DOM. It still fires the callback even though the element is outside of the DOM.
The issue should be solved if you clean up your view properly
Polymer({
ready: function(){
// add listeners
window.addEventListener('goUrl', this.navigation);
},
detached: function(){
// remove listeners
window.removeEventListener('goUrl', this.navigation);
},
...
});
I'm currently trying to build an app using backbone, require.js & jqm. I'm new to jquery mobile an I'm having strange rendering issues and I'm not able to track them down or fix them. So my question remains on a rather nebulous and phenomenal level - hopefully someone can help me out here. I've the feeling that I understood something wrong here.
So here's what I do:
Basically I'm using the router facilities of backbone.js and disabling all routing capabilities of jqm. Using (in main.js):
$.mobile.ajaxEnabled = false;
$.mobile.linkBindingEnabled = false;
$.mobile.hashListeningEnabled = false;
$.mobile.pushStateEnabled = false;
After that I use the routing technique proposed by Christophe Coenraets on his blog. Which basically looks like this:
var AppRouter = Backbone.Router.extend({
// Router constructor
initialize: function(){
this.loginView = new LoginView(this);
this.registerView = new RegisterView(this);
this.user = new User(this);
// Tell Backbone to listen for hashchange events
Backbone.history.start();
},
// Define routes
routes: {
'': 'home',
'login' : 'login',
'registration' : 'registration',
},
/// Define route actions ///
// Home route
home: function() {
this.user.isUserLoggedIn();
},
// Login route
login: function() {
console.log("Welcome to the router - login route.");
this.changePage(this.loginView);
},
registration:function() {
console.log("Welcome to the router - registration route.");
this.changePage(this.registerView);
},
changePage:function (page) {
$("body").empty();
$(page.el).attr('data-role', 'page');
$("body").append($(page.el));
page.render();
$(":mobile-pagecontainer").pagecontainer("change", $(page.el), {transition: "pop", changeHash: false, reverse: false});
}});
Basically I've to views: The Login & RegisterView at the moment. When I naviagte to the RegisterView it works fine, but navigating backwards to login I can see the transition ("pop") - but after the transition the content is not shown in the browser. It is present in the DOM but I figures out that certain css classes are missing for example "ui-page-active" on the data-role="page". When I apply that class manually I can see the LoginView but all events are lost (a click on the registration tab does not trigger anything).
I've the feeling that there is a conceptual misunderstanding on my side and I'm not able to figure out where the problem resides. I tried things like .trigger("create") but that looked rather like a helpless tryout than anything else.
I've set up a GitHub-Repository. I'm thankful for any help - thanks in advance and sorry for the confused question.
EDIT: Yeah... and here also the link to the repo.
I figured out, that I placed the configuration to prevent jqm in the wrong place. It has to reside in main.js before the actual app is loaded:
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;
});
require([
// Load our app module and pass it to our definition function
'app',
], function(App){
// The "app" dependency is passed in as "App"
// Again, the other dependencies passed in are not "AMD" therefore don't pass a parameter to this function
App.initialize();
});
});
Thanks for the help anyways.
I am trying to learn some javascript and I've gone through several tutorials, now I'm trying to understand a real-life system. Here is a demo site that has been pretty well put together:
http://nodecellar.coenraets.org/
https://github.com/ccoenraets/nodecellar
I think I understand the basics of how events can be assigned to elements on the page but then when I look through his source code I can't figure out how even the first click works. When you click "Start Browsing" it should be caught by javascript somehow which fires off an asynchronous request and triggers the view to change with the data received. But in his / public/js/views/ nowhere is there event catching plugged in (except in the itemdetail view but that's a different view entirely).
I also tried using chrome developer tools to catch the click and find out what script caught it.
Under sources I tried setting an event breakpoint for DOM mutation and then clicked.... but no breakpoint (how is that possible? There's definitely a DOM mutation happening)
I then went under elements and checked under the "click" event listener and didn't see anything revealing there either.
Obviously I don't know what I'm doing here. Can anyone help point me in the right direction?
This app is using backbones routing capabilities to switch contexts.
It is basically using hash tags and listening for location change events to trigger updates to the page.
The routing configuration is in main.js:
See: Backbone.Router for more information.
Code Reference: http://nodecellar.coenraets.org/#wines
var AppRouter = Backbone.Router.extend({
routes: {
"" : "home",
"wines" : "list",
"wines/page/:page" : "list",
"wines/add" : "addWine",
"wines/:id" : "wineDetails",
"about" : "about"
},
initialize: function () {
this.headerView = new HeaderView();
$('.header').html(this.headerView.el);
},
home: function (id) {
if (!this.homeView) {
this.homeView = new HomeView();
}
$('#content').html(this.homeView.el);
this.headerView.selectMenuItem('home-menu');
},
list: function(page) {
var p = page ? parseInt(page, 10) : 1;
var wineList = new WineCollection();
wineList.fetch({success: function(){
$("#content").html(new WineListView({model: wineList, page: p}).el);
}});
this.headerView.selectMenuItem('home-menu');
},
// etc...
});
utils.loadTemplate(['HomeView', 'HeaderView', 'WineView', 'WineListItemView', 'AboutView'], function() {
app = new AppRouter();
Backbone.history.start();
});