Here is my view:
define([
'jquery',
'underscore',
'backbone',
'models/tableModel',
'collections/tablesCollection',
'views/tablesView'
], function($, _, Backbone, tableModel, tablesCollection, tablesView) {
require(['collections/tablesCollection'], function(tablesCollection) {
var t = new tablesCollection(null, {url: 'main-contact'});
var tables = new tablesView({ collection: t, template: 'main-contact-template'});
tables.url = 'main-contact';
return tables; // <!-- returns view, tables can be console.log'ed
});
console.log(tables); // <!-- tables is not defined
});
How do I get the tables within the require statement so that is accessible where the console.log is? This seems to be where I need to return the view from, so I can use it in my route:
app_router.on('route:index', function(){
require(['views/tables/mainContactView'], function(mainContactView) {
console.log(mainContactView); // <!-- undefined, unless some value is returned from where the console.log() is above
$('#web-leads').html(mainContactView.render().el);
});
});
If I put return 'test' where the console.log(tables) is, I can console.log() it in my route. So I assume that's where I need to return the view from. How do I pass that data out? Right now, even with a return statement, my view is undefined. I need to get the view out of the require. How do I do that?
You've already loaded collection/tablesCollection in define, so you don't have to do another require to get it loaded.
You can simply the definition of the View as this:
define([
'jquery',
'underscore',
'backbone',
'models/tableModel',
'collections/tablesCollection', // You've already required tablesCollection here.
'views/tablesView'
], function($, _, Backbone, tableModel, tablesCollection, tablesView) {
var t = new tablesCollection(null, {url: 'main-contact'});
var tables = new tablesView({ collection: t, template: 'main-contact-template'});
tables.url = 'main-contact';
return tables;
});
Related
Does anyone have pointers for using Backbone.Epoxy ( epoxy.js ) with HTML passed in via template.
aka given a View such as
define([
'jquery',
'underscore',
'backbone',
'epoxy',
'text!views/MyTemplate.html'
], function($, _, Backbone, Epoxy, Template ){
var MyView = Epoxy.View.extend({
template: _.template(Template),
bindings: {
".brand-name": "text:name",
".brand-name": "text:count",
},
// Perhaps render not needed given that epoxy bindings
render : function() {
var data = {
item: this.model,
_: _
};
this.$el.html( this.template(data) );
return this;
}
return MyView;
});
which renders the template but without any bindings.
and does one need a render method anymore..!
No you don't need the render method, just instantiate you view.
var view = new BindingView({model: bindModel});
Here is an example
But when you use the render method and replace the view.el you lost those bindings, in that case try to do :
this.$el.html( this.template(data) );
this.applyBindings();
Question Updated
I am implementing a search and result for the same in the same page. i
have two seperate html views and views for search and result.
Here is what is happening..
From my router the below view is loaded. This view will load two other views called search and result. I have included the respective html views in the seperate views. but when i run the proj, it displays nothing.
Am i rendering the view in this file wrong ??
if i am rendering it wrong can somebody please tell me where is the mistake and how to rectify it ??
should i include the respective html templates of search and result also in this file ??
views.driver.search.js :
define(
[ 'jquery',
'underscore',
'backbone',
'app/models/model.driver',
'app/collections/collection.driver',
'app/models/model.driver.searchform',
'app/dashboard/views.driver.searchForm',
'app/models/model.driver.searchresult',
'app/dashboard/views.driver.searchResults',
],
function ($, _, Backbone, DriverModel,SearchResultCollection ,searchFormModel, searchFormView, SearchResultModel,SearchResultView) {
var DriverSearchView = Backbone.View.extend({
el: $('#content'),
initialize: function(){
this.render();
},
render: function () {
// var compiledTemplate = _.template(searchFormTemplate, {});
// this.$el.html(compiledTemplate);
this.searchFormInitModel = new searchFormModel();
var searchformView = new searchFormView({model:this.searchFormInitModel});
this.$("#content").html(searchformView.render());
var driver1 = new DriverModel({id:1,firstName:"driver1",lastName:'last',dob:'12/12/12001',});
var driver2 = new DriverModel({id:2,firstName:"driver2",lastName:'last',dob:'12/12/12001',});
var driver3 = new DriverModel({id:3,firstName:"driver3",lastName:'last',dob:'12/12/12001',});
var driver4 = new DriverModel({id:4,firstName:"driver3",lastName:'last',dob:'12/12/12001',});
this.searchResultCollection= new SearchResultCollection([driver1, driver2, driver3, driver4]);
var searchResultView = new SearchResultView({el:this.$el.find("#searchResult"),collection:this.searchResultCollection});
this.$("#content").html(searchResultView.render());
//this.$el.find("#searchResult").html(searchResultView.render());
}
}); // Our module now returns our view
return DriverSearchView;
});
I don't see an issue with your workflow. Reason you are not seeing your console.logs, is because you are returning an object literal containing your initialize function without actually calling the function. Is there a reason you need to return an object from your initialize module?
Anyhow, I am not entirely sure how you calling your app.js file, but try the following if you do not need to return an object back from your initialize module
define(
[
'jquery',
'underscore',
'backbone',
'app/router',
// 'datatable'
],
function ($, _, backbone, router){ //,datatable) {
var initialize = (function () {
console.log("App1");
debugger;
console.log("App2");
router.initialize();
console.log("App3");
})();
// Depending what you want to do here, you could just
// console.log("Router initialized...");
// router.initialize();
});
I'm laying out the basic structure and just started to create models. The issue is that the reference to the initialized Stackmob is lost within the model.
main.js
require(['modernizr','jquery','backbone', 'underscore', 'routers/router', 'stackmob'], function(Modernizr, $, Backbone, _, Router, Stackmob) {
StackMob.init({
appName: {appName},
clientSubdomain: {clientSubdomain},
apiVersion: 0
});
// Instantiates a new Router
this.router = new Router();
});
Model.js
define(['jquery', 'backbone', 'stackmob', 'models/business'], function($, Backbone, Stackmob, Business) {
var BusinessesCollection = StackMob.Collection.extend({
model: Business,
// Model Constructor
initialize: function() {
}
});
// Returns the Model class
return BusinessesCollection;
});
How can I get the initialized StackMob object to be accessible to the model module?
Introduce a sort of instance of StackMob?
my-stackmob.js
define(['stackmob'], function(StackMob) {
StackMob.init({
appName: {appName},
clientSubdomain: {clientSubdomain},
apiVersion: 0
});
// return a particular StackMob that we've initialised
return StackMob;
});
main.js
(would not appear to use StackMob directly any more, based on your example code)
require(['modernizr','jquery','backbone', 'underscore', 'routers/router'], function(Modernizr, $, Backbone, _, Router) {
// Instantiates a new Router
this.router = new Router();
});
Model.js
(uses my-stackmob)
define(['jquery', 'backbone', 'my-stackmob', 'models/business'], function($, Backbone, Stackmob, Business) {
var BusinessesCollection = StackMob.Collection.extend({
model: Business,
// Model Constructor
initialize: function() {
}
});
// Returns the Model class
return BusinessesCollection;
});
So I'm working on a backbone app, and trying to modularize things as much as I can using require.js. This has been my guide.
I'm having trouble getting my view to always fetch my collection. If I access my app from the base url (myapp.com/), and go to the route of my view, the collection is fetched. If I do not go to the view, and instead access it from myapp.com/#/campaigns, then the collection is not fetched.
Here is some relevant code.
router.js
define([
'jQuery',
'Underscore',
'Backbone',
'views/home/main',
'views/campaigns/list'
], function($, _, Backbone, mainHomeView, campaignListView ){
var AppRouter = Backbone.Router.extend({
routes: {
// Define some URL routes
'campaigns': 'showCampaigns',
// Default
'*actions': 'defaultAction'
},
showCampaigns: function(){
campaignListView.render();
},
defaultAction: function(actions){
// We have no matching route, lets display the home page
//mainHomeView.render();
}
});
var initialize = function(){
var app_router = new AppRouter;
Backbone.history.start();
};
return {
initialize: initialize
};
});
collections/campaigns.js
define([
'jQuery',
'Underscore',
'Backbone',
'models/campaigns'
], function($, _, Backbone, campaignsModel){
var campaignsCollection = Backbone.Collection.extend({
model: campaignsModel,
url: '/campaigns',
initialize: function(){
}
});
return new campaignsCollection;
});
views/campaigns/list.js
define([
'jQuery',
'Underscore',
'Backbone',
'collections/campaigns'
], function($, _, Backbone, campaignsCollection){
var campaignListView = Backbone.View.extend({
el:$('#container'),
initialize:function(){
this.collection = campaignsCollection;
this.collection.fetch();
},
render: function(){
var data = {
campaigns: this.collection,
_: _
};
$('#container').html('Campaigns length: '+data.campaigns.models.length);
}
});
return new campaignListView;
});
Any ideas on what I'm doing wrong? I believe it has something to do with calling this.collection.fetch() in the initalize function of the view. If that is the issue, where should I put fetch()?
The problem in your code is that your campaignListView fetch the collection when it is initialized and it is initialized only once. Your render method which is actually called from the router doesn't call your initialize method of campaignListView, when you change theurl your second time.
You have two options here :
1. return the class not the instance of your campaignListView and initialize it in the router :
// in your router code
showCampaigns: function(){
var campaignListViewInstance = new campaignListView(); // don't forget the brackets after your initialize function
campaignListViewInstance.render();
},
// in your campaignListView code :
return campaignListView; // without "new"
This will initialize the code everytime the router is hit.
2. place your fetch in the render method
// in your campaignListView code :
initialize:function(){
this.collection = campaignsCollection;
},
render: function(){
this.collection.fetch({success: function(collection) {
var data = {
campaigns: collection,
_: _
};
$('#container').html('Campaigns length: '+data.campaigns.models.length);
}); // this will be fetched everytime you render and also it has success callback
}
Also be aware that you should replace all your instance creating functions with brackets at the end
return new campaignListView; --> return new campaignListView();
return new campaignsCollection; --> return new campaignsCollection();
Another problem you will face is the async work of fetch. You should use success or event driven rendering of your collection, because fetch works in the background and you will have no data when you immediately call render after calling fetch.
+1 for your AMD approach.
I should really update the tutorial but it's better to not return instantiated modules. Maybe try checking out http://backboneboilerplate.com
I built file structure for javascript game using RequireJs and Backbone. Now I have problem to combine it with Box2DWeb.
// Filename: game/controller/arena.js
define([
'jquery',
'underscore',
'backbone',
'_69_',
'game/controller/object',
'game/model/arena',
'game/view/arena',
'box2d'
], function($, _, Backbone, _69_, Object, Model, View, Box2D){
var ArenaController = Object.extend ({
init : function (){
this._super(Model, View);
this.world = new b2World(
new b2Vec2(0, 10) //gravity
, true //allow sleep
);
this.appView;
this.loops=0;
},
start : function (){
_69_.l('start')
},
update :function (){
_69_.l('update')
},
stop : function (){
_69_.l('stop')
}
});
return new ArenaController;
});
But in console I get that b2World is not defined. What i should do to get it work?
I dont know box2d but box2world does indeed not exist in that context unless it is a global object.
I presume here that you will need its namespace, if it is included in the box2d reference you defined in the required.js dependencies you might use
new Box2D.b2World(...);
you should try to including "box2D" in the require of your main.js file. Box2D will load as a global object which you can use later.
require([
'app',
'box2d'
], function(app){
app.init();
});
You shouldn't mention it in the function or you could list it as "ignore":
require([
'app',
'box2d'
], function(app, ignore){
app.init();
});
In the Chrome console, you could type Box2D and you should see it pop up as a global object. Once you know its global, you can start using it.
Then in your ArenaController you can list "box2d" in the define array but not in the function:
define([
'jquery',
'underscore',
'backbone',
'_69_',
'game/controller/object',
'game/model/arena',
'game/view/arena',
'box2d'
], function($, _, Backbone, _69_, Object, Model, View) {
var ArenaController = Object.extend ({
init : function (){
this._super(Model, View);
var b2World = Box2D.Dynamics.b2World; //Box2D should be available as a global
this.world = new b2World(
new b2Vec2(0, 10) //gravity
, true //allow sleep
);
this.appView;
}
});
return new ArenaController;
});