I am working on javascript backbone project. I declared a global object like follow
window.App = { Vent: _.extend({}, Backbone.Events) }
I did above in initialize function like following
initialize: function () {
window.App = { Vent: _.extend({}, Backbone.Events), hello: 'yes' };
console.log(App); // This is ONE. see explanation below for ONE
console.log(App.Vent); // This is TWO. see explanation below
}
ONE
This log line shows following
function (){return parent.apply(this,arguments)} app.js:22
TWO
This log line show
undefined
Also if I do console.log(App.hello) it still says undefined
Please help me what am I doing wrong in this code?
Update
Here is all the related code to my problem. I am using requirejs and backbone
here is my main.js
require(['domReady', 'views/app', 'jqm'], function (domReady, AppView) {
domReady(function () {
window.App = { Vent: _.extend({}, Backbone.Events) };
new AppView();
});
});
here is views/app.js file
define(['backbone', 'views/home/homes', 'collections/homes'], function (Backbone, HomesView, HomesCollection ) {
var App = Backbone.View.extend({
el: 'div#page',
events: {
'swipeleft': 'nextView',
'swiperight': 'preView'
},
nextView: function (e) {
console.log(App.Vent);
//App.Vent.trigger('changeView', { direction: 'next' });
},
preView: function (e) {
console.log(App.Vent);
//App.Vent.trigger('changeView', { direction: 'prev' });
}
});
return App;
});
What I am doing in this file is when user swipes left or right then it calls nextView and preView functions. In these functions I want to trigger and Event which I listen to them in another view. But right now I want to console it. But it says undefined
Try to change:
var App = Backbone.View.extend({
to something else. Like this:
var iApp = Backbone.View.extend({
Related
could you please tell me how to navigate from one page to another page in backbone .
I want to show second html on button click how it is possible
I so like that .I resister event like that
events: {
'click #click':'moveTonext'
},
moveTonext: function(){
alert('---')
},
I make second page like that
define([
'jquery',
'underscore',
'backbone',
'text!templates/second.html'
], function ($, _, Backbone, statsTemplate) {
'use strict';
var secondView = Backbone.View.extend({
// Instead of generating a new element, bind to the existing skeleton of
// the App already present in the HTML.
el: '#todoapp',
// Compile our stats template
template: _.template(statsTemplate),
// Delegated events for creating new items, and clearing completed ones.
events: {
},
// At initialization we bind to the relevant events on the `Todos`
// collection, when items are added or changed. Kick things off by
// loading any preexisting todos that might be saved in *localStorage*.
initialize: function () {
this.render();
},
serialize: function () {
return {
message: 'world'
};
},
// Re-rendering the App just means refreshing the statistics -- the rest
// of the app doesn't change.
render: function () {
this.$el.html(this.template());
}
// Add a single todo item to the list by creating a view for it, and
// appending its element to the `<ul>`.
});
return secondView;
})
Second html
<h1>second</h1>
here is my plunker
http://plnkr.co/edit/fCXwSrroJP1l6BppjpmD?p=preview
Basically your button should trigger navigation, so the click handler should look like this:
moveToNext: function () {
router.navigate("other/path", { trigger: true });
}
Then, in your router code you need to add a route handler for the above path:
routes: {
"other/path": "handleOtherPath"
},
handleOtherPath: function () {
new SecondView();
}
This is for the case when SecondView should replace FirstView. If it should be appended instead, the following mechanism can be used:
moveToNext: function () {
new SecondView({ el: this.$(secondViewContainerSelector) });
}
Here's a working Plunker sample.
I am trying to add an WatchList feature in the existing code discourse ember rails application
I have addded the following code
Discourse.Route.buildRoutes(function() {
var router = this;
this.resource('watchLists', { path: '/watch_lists' }, function() {
this.resource('watchList', {path: ':watch_list_id'});
});
});
In the ember Controller
Discourse.WatchListsController = Discourse.ObjectController.extend({});
In the ember model
Discourse.WatchList = Discourse.Model.extend({});
Discourse.WatchList.reopenClass({
find: function() {
jQuery.getJSON("watch_lists").then(function(json) {
var watch_lists = json.watch_lists.map(function(attrs) {
return Discourse.WatchList.create(attrs);
});
});
In the ember view js
Discourse.WatchListsView = Ember.View.extend({});
In ember route js
Discourse.WatchListsRoute = Discourse.Route.extend({
model: function() {
return Discourse.WatchList.find();
}
});
When i renderring the handlebars template I am getting an WatchListsController object withot the data we have got from the ajax.
Can any body point out where i am doing wrong.
I see two possible problems.
First, you probably want WatchListsController to extend Discourse.ArrayController, not Discourse.ObjectController.
Second your reopen block is not valid JavaScript in the example code that you posted. I count four { but only two }. You probably want something kind of like this:
Discourse.WatchList.reopenClass({
find: function() {
return jQuery.getJSON("watch_lists").then(function(json) {
return json.watch_lists.map(function(attrs) {
return Discourse.WatchList.create(attrs);
}
});
}
});
Scenario
I am making app using backbonejs, requirejs and jquery. I am retrieving data from remote server. Once the data is fetched, then I want to display it to the user.
Problem
First I fetch data inside app.js file then I make a instance of MoviesView and pass collection in to this view. Inside MoviesView, I have initialize function and inside this function I am listening to an Event triggered by router. Once that event is listened then it should call renderAll function. The problem lies here, it does not invoke renderAll function at all.
My code
here is function where I am fetching data from the server
fetchBoxOfficeMovies: function () {
var movieCollection = new MoviesCollection;
movieCollection.fetch({success: this.successCallback, error: this.errorCallback}).then(function () {
//console.log(movieCollection.toJSON());
new MoviesView({ collection: movieCollection });
});
},
successCallback: function () {
console.log('successCallback');
},
Here is the router where I am triggering an event
routes: {
'': 'index'
},
index: function () {
App.Vent.trigger('init');
console.log('router');
}
And here is initialize and renderAll functions inside MoviesView
initialize: function () {
App.Vent.on('init', this.renderAll, this);
console.log('movies view');
},
renderAll: function () {
console.log('renderAll');
},
Output which I see in my console
Here is what I see in my console
router
successCallback
movies view
As you can see I do not see renderAll in my console.
Question
Why don't I see renderAll and how can I fix this?
UPDATE
Here is my entire App view
var App = Backbone.View.extend({
el: 'body',
initialize: function () {
App.router = new MainRouter();
Backbone.history.start();
this.fetchBoxOfficeMovies();
},
fetchBoxOfficeMovies: function () {
var movieCollection = new MoviesCollection;
movieCollection.fetch({success: this.successCallback, error: this.errorCallback}).then(function () {
//console.log(movieCollection.toJSON());
new MoviesView({ collection: movieCollection });
});
},
successCallback: function () {
console.log('successCallback');
},
errorCallback: function () {
console.log('errorCallback');
}
});
As it can be seen that I am making new instance of MainRouter before calling fetchBoxOfficeMovies, which means I am triggering event before everything else.
As DCoder said, you got the order wrong. Rename your console.log to understand better what's happening.
router -> I trigger a 'init' event
successCallback -> successCallback
movies view -> I start listening 'init' events NOW
Suggested 'Fix':
movieCollection.fetch({
success: this.successCallback,
error: this.errorCallback
}).then(function () {
//console.log(movieCollection.toJSON());
var moviesView = new MoviesView({ collection: movieCollection });
moviesView.renderAll()
});
I'm trying to create a Spine's Controller and init() it,
jQuery(function($) {
window.Tests = Spine.Controller.create({
init: function() {
console.log('Tests created!');
}
});
window.App = Tests.init();
});
but I have an error
Uncaught TypeError: Object function result() {
return result.super.constructor.apply(this, arguments);
} has no method 'init'
Spine is included before my Controller's file.
Help me to solve it, why Controller.create() (and Controller.sub()) returns function and not an object?
I've tried to make it like in example:
jQuery(function($){
window.App = Spine.Controller.create({
el: $("body"),
elements: {
"#sidebar": "sidebarEl",
"#contacts": "contactsEl"
},
init: function(){
this.sidebar = Sidebar.init({el: this.sidebarEl});
this.contact = Contacts.init({el: this.contactsEl});
Contact.fetch();
}
}).init();
});
I solved it by doing
new Tests();
In the Backbone.js documentation, in the entry for the Router.routes method, it is stated
When the visitor presses the back button, or enters a URL, and a particular route is matched,
the name of the action will be fired as an event, so that other objects can listen to the router,
and be notified.
I have attempted to implement this in this relatively simple example:
The relevant JS:
$(document).ready(function(){
// Thing model
window.Thing = Backbone.Model.extend({
defaults: {
text: 'THIS IS A THING'
}
});
// An individual Thing's View
window.ThingView = Backbone.View.extend({
el: '#thing',
initialize: function() {
this.on('route:showThing', this.anything);
},
anything: function() {
console.log("THIS DOESN'T WORK! WHY?");
},
render: function() {
$(this.el).html(_.template($('#thing-template').html(), {
text: this.model.get('text')
}));
return this;
}
});
// The Router for our App
window.ThingRouter = Backbone.Router.extend({
routes: {
"thing": "showThing"
},
showThing: function() {
console.log('THIS WORKS!');
}
});
// Modified from the code here (from Tim Branyen's boilerplate)
// http://stackoverflow.com/questions/9328513/backbone-js-and-pushstate
window.initializeRouter = function (router, root) {
Backbone.history.start({ pushState: true, root: root });
$(document).on('click', 'a:not([data-bypass])', function (evt) {
var href = $(this).attr('href');
var protocol = this.protocol + '//';
if (href.slice(protocol.length) !== protocol) {
evt.preventDefault();
router.navigate(href, true);
}
});
return router;
}
var myThingView = new ThingView({ model: new Thing() });
myThingView.render();
var myRouter = window.initializeRouter(new ThingRouter(), '/my/path/');
});
The relevant HTML:
<div id="thing"></div>
<!-- Thing Template -->
<script type="text/template" id="thing-template">
<a class='task' href="thing"><%= text %></a>
</script>
However, the router event referenced in the View's initialize function does not seem to get picked up (everything else works--I'm successfully calling the "showThing" method defined in the Router).
I believe I must have some misconception about what the documentation intended by this statement. Therefore, what I'm looking for in a response is: I'd love to have someone revise my code so that it works via a Router event getting picked up by the View, or, clearly explain what the Router documentation I listed above intends us to do, ideally with an alternative code sample (or using mine, modified).
Many thanks in advance for any assistance you can provide!
This is beacuse you are binding a listener to the wrong object. Try this in your View :
window.ThingView = Backbone.View.extend({
initialize: function() {
myRouter.on('route:showThing', this.anything);
},
...